如何使用代码契约指示方法永远不会返回 null?
如何指示一个方法永远不会返回 null? 目前这是我的代码。
第 19 行收到 Ensures notproved 消息,即使 CreateFunction 假设结果不是空的。
1 <Pure()> Public Function CreateFunction(Of TArg1, TArg2, TResult)(ByVal body As Func(Of Expression, Expression, BinaryExpression)) As Func(Of TArg1, TArg2, TResult)
2 Contract.RequiresAlways(body IsNot Nothing)
3 Contract.Assume(Contract.Result(Of Func(Of TArg1, TArg2, TResult))() IsNot Nothing)
4
5 Dim arg1 = Expression.Parameter(GetType(Integer), "arg1")
6 Dim arg2 = Expression.Parameter(GetType(Integer), "arg2")
7
8
9 Dim temp = Expression.Lambda(body(arg1, arg2), arg1, arg2)
10 Contract.Assume(temp IsNot Nothing)
11 Return DirectCast(temp.Compile, Global.System.Func(Of TArg1, TArg2, TResult))
12 End Function
13
14 <Pure()> Public Function Add() As Func(Of T, T, T)
15 Contract.Ensures(Contract.Result(Of Func(Of T, T, T))() IsNot Nothing)
16
17 Dim temp = CreateFunction(Of T, T, T)(AddressOf Expression.AddChecked)
18 Return temp
19 End Function
How do I indicate that a method never returns a null? Currently this is my code.
Line 19 gets an Ensures not proven message, even though CreateFunction assumes that the result is not nothing.
1 <Pure()> Public Function CreateFunction(Of TArg1, TArg2, TResult)(ByVal body As Func(Of Expression, Expression, BinaryExpression)) As Func(Of TArg1, TArg2, TResult)
2 Contract.RequiresAlways(body IsNot Nothing)
3 Contract.Assume(Contract.Result(Of Func(Of TArg1, TArg2, TResult))() IsNot Nothing)
4
5 Dim arg1 = Expression.Parameter(GetType(Integer), "arg1")
6 Dim arg2 = Expression.Parameter(GetType(Integer), "arg2")
7
8
9 Dim temp = Expression.Lambda(body(arg1, arg2), arg1, arg2)
10 Contract.Assume(temp IsNot Nothing)
11 Return DirectCast(temp.Compile, Global.System.Func(Of TArg1, TArg2, TResult))
12 End Function
13
14 <Pure()> Public Function Add() As Func(Of T, T, T)
15 Contract.Ensures(Contract.Result(Of Func(Of T, T, T))() IsNot Nothing)
16
17 Dim temp = CreateFunction(Of T, T, T)(AddressOf Expression.AddChecked)
18 Return temp
19 End Function
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有效吗
? 基本上,我会尝试将其削减,直到找到最简单的情况,但不能按您的预期工作,然后从那里开始。
——马库斯Q
Does
work? Basically, I'd try paring it down till you find the simplest case that doesn't work as you'd expect and go from there.
-- MarkusQ
您需要将
CreateFunction
中的Assume
更改为Ensures
。 之后你应该没事了。 请记住,Assume
用于内部假设,以便在本地帮助静态检查器。 从其他方法中看不到它们。 只有Requires
和Ensures
是跨方法合约。You need to change the
Assume
inCreateFunction
to anEnsures
. After that you should be okay. Remember,Assume
is for internal assumptions in order to help the static checker locally. They are not visible from other methods. OnlyRequires
andEnsures
are cross-method contracts.