考虑以下代码:
int SomeField;
void Foo([Pure] Func<int, object> getData)
{
Contract.Requires(getData != null);
Contract.Requires(getData(this.SomeField) != null);
}
我收到以下警告:
Detected call to method '
System.Func'2<System.Int32,System.Object>.Invoke(System.Int32)
' without[Pure]
in contracts of method '....Foo(System.Func'2<System.Int32,System.Object>)
'
这个警告非常有道理。但我仍然想在契约(Contract)中调用委托(delegate)而不是收到警告(假设我有警告变成错误)。我该如何实现?
我尝试了属性 Pure
,如示例所示,但这不起作用。
我还想知道为什么 PureAttribute
可以在参数上指定。如果参数的类型不是委托(delegate)类型,那将毫无意义,即使是,它也不会像我预期的那样工作,正如我上面所说的。
最佳答案
使用当前的代码契约库来实现这一点的方法是声明您自己的委托(delegate)类型,如下所示:
[Pure]
public delegate U PureFunc<in T, out U>(T thing);
我认为它对委托(delegate)参数不起作用的原因是通常很难检查 :)
关于c# - 如何告诉代码契约(Contract)指定为参数的委托(delegate)是纯的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4987350/