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

本文关键字:抛出异常 pure 函数 | 更新日期: 2023-09-27 18:15:27

对于可以抛出异常的函数是否可以具有[pure]属性?

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

根据

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

PureAttribute属性

表示类型或方法是纯的,即不生成任何类型或方法可见状态变化

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

// 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异常

你可以抛出一个异常,你没有做任何可见的状态改变。这里的例子来自参考源

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

我同意Dmitry的观点。

根据msdn的文档:

在契约中调用的所有方法必须是纯方法;也就是说,它们不能更新任何先前存在的状态。纯方法允许修改在进入纯方法后创建的对象。

抛出异常是允许的,并不一定会被认为是在改变对象状态。