gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:46:35 27 4
gpt4 key购买 nike

可以抛出异常的函数可以有[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 anyvisible 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 异常

关于c# - [纯] 函数可以抛出异常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40305162/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com