[纯] 函数可以抛出异常吗?

Can a [pure] function throw an exception?

一个可以抛出异常的函数可以有[pure]属性吗?

根据

https://msdn.microsoft.com/en-us/library/system.diagnostics.contracts.pureattribute(v=vs.110).aspx

PureAttribute 属性

Indicates that a type or method is pure, that is, it does not make any visible state changes.

所以很可能从这样的方法中抛出异常,例如

// factorial is a pure function: no state will be changed, 
// just a computation 
[Pure]
public static BigInteger Factorial(BigInteger value) {
  // We can't return infinity with BigInteger and that's why have to throw the exception 
  if (value < 0)
    throw new ArgumentOutOfRangeException("value", "value must be non-negative"); 

  ...
}

如果我将这个纯方法称为

  BigInteger result = Factorial(1000000000);

可能的结果之一是 OutOfMemory 抛出异常

我同意德米特里的观点。

根据 msdn 的文档:

All methods that are called within a contract must be pure; that is, they must not update any preexisting state. A pure method is allowed to modify objects that have been created after entry into the pure method.

抛出异常是允许的,不一定会被视为更改对象状态。

您可以抛出异常,您没有进行任何可见的状态更改。这里的示例来自 Reference source.

    [Pure]
    private void VerifyWritable() {
        if (isReadOnly) {
            throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_ReadOnly"));
        }
        Contract.EndContractBlock();
    }