如何告诉代码合约指定为参数的委托是 Pure 的?
考虑以下代码:
int SomeField;
void Foo([Pure] Func<int, object> getData)
{
Contract.Requires(getData != null);
Contract.Requires(getData(this.SomeField) != null);
}
我收到以下警告:
检测到在合约中没有
[Pure]
的情况下对方法“System.Func'2
”的调用方法 '.....Invoke(System.Int32) Foo(System.Func'2
')
此警告非常有道理。但我仍然想打电话给合同中的代表,而不是收到警告(假设我的警告变成了错误)。我该如何实现这一目标?
我尝试了属性 Pure
,如示例所示,但这不起作用。
我还想知道为什么可以在参数上指定 PureAttribute
。如果参数的类型不是委托类型,那就没有意义,即使是委托类型,它也不会像我预期的那样工作,正如我上面所说的。
Consider the following code:
int SomeField;
void Foo([Pure] Func<int, object> getData)
{
Contract.Requires(getData != null);
Contract.Requires(getData(this.SomeField) != null);
}
I get the following warning:
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>)
'
This warning makes perfect sense. But I'd still like to call the delegate in contracts and not get a warning (suppose I had warnings turned into errors). How do I achieve that?
I tried the attribute Pure
, as shown in the example, but that doesn't work.
I'd also like to know why the PureAttribute
can be specified on parameters. It wouldn't make sense if the type of the parameter wasn't a delegate type, and even if it is, it doesn't work as I'd expect, as I stated above.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用当前的 Code Contracts 库执行此操作的方法是声明您自己的委托类型,如下所示:
我认为它不适用于委托参数的原因是一般情况下很难检查:)
The way to do this with the current Code Contracts library is to declare your own delegate type, like this:
I think that the reason it doesn't work on delegate parameters is that it would be very hard to check in general :)
我不习惯合约框架,但从纯粹逻辑的角度来看,委托不可能是纯粹的,仅仅因为它可以采用任何方法来实现签名。您无法保证所有方法都适合该委托,因为它只需要一个方法即可打破合同。
I'm not accustomed to the contracts framework, but from a purely logical way a delegate can't be pure, simply because it can take any method fulfilling the signature. There is no way you can guarentee that for all methods fitting that delegate, as it only requires one to break the contract.