如何告诉代码合约指定为参数的委托是 Pure 的?

发布于 2024-10-17 08:53:25 字数 721 浏览 0 评论 0原文

考虑以下代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

说好的呢 2024-10-24 08:53:25

使用当前的 Code Contracts 库执行此操作的方法是声明您自己的委托类型,如下所示:

[Pure]
public delegate U PureFunc<in T, out U>(T thing);

我认为它不适用于委托参数的原因是一般情况下很难检查:)

The way to do this with the current Code Contracts library is to declare your own delegate type, like this:

[Pure]
public delegate U PureFunc<in T, out U>(T thing);

I think that the reason it doesn't work on delegate parameters is that it would be very hard to check in general :)

一片旧的回忆 2024-10-24 08:53:25

我不习惯合约框架,但从纯粹逻辑的角度来看,委托不可能是纯粹的,仅仅因为它可以采用任何方法来实现签名。您无法保证所有方法都适合该委托,因为它只需要一个方法即可打破合同。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文