如何要求委托始终返回非空值? [英] How do I require that a delegate always returns non-null values?

查看:123
本文介绍了如何要求委托始终返回非空值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:


< Extension()> 
公共函数F(ByVal arg As Func(Of Object))As Object
Contract.Requires(arg IsNot Nothing)
Contract.Ensures(Contract.Result(Of Object)()IsNot Nothing )
'要求arg()并非一无所获;但函数可能涉及状态或参数,所以我们必须静态检查它
返回arg()
结束函数

解决方案

目前,我们没有为您提供在委托上指定合同的方法。在这种情况下,你将不得不使用Contract.Assume。

Dim result = arg()
Contract.Assume(结果IsNot Nothing)
返回结果

我们计划允许您为您定义的委托类型编写合同类(就像接口一样)。但这意味着委托类型的合同是固定的。

在您提供的示例中,这对您没有帮助,因为您正在重用Func委托类型。在这里你需要一个关于Func的特定使用的特定合同,这更难以处理。一个人遇到各种编码问题(重复包装代表)进行运行时检查。

我们必须看看我们能做些什么。


For example:

        <Extension()>
        Public Function F(ByVal arg As Func(Of Object)) As Object
            Contract.Requires(arg IsNot Nothing)
            Contract.Ensures(Contract.Result(Of Object)() IsNot Nothing)
            'requires arg() isnot nothing; but the function might involve state or arguments so we have to check it statically
            Return arg()
        End Function

解决方案

Currently, we don't provide you with a way to specify the contract on delegates. In this case, you'll have to use a Contract.Assume.

Dim result = arg()
Contract.Assume( result IsNot Nothing )
Return result

We are planning to allow you to write contract classes for delegate types you define (just like for interfaces). But that means the contract of the delegate type is fixed.

In the example you provide, this wouldn't help you, as you are reusing the Func delegate type. Here you would need a specific contract on this particular use of Func, which is much more difficult to handle. One gets into all sorts of encoding problems (repeated wrapping of delegates) for runtime checking.

We'll have to see what we can do about it.


这篇关于如何要求委托始终返回非空值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆