我怎么能证明一个方法永远不会在C#(契约式设计)返回null [英] How can I show that a method will never return null (Design by contract) in C#

查看:113
本文介绍了我怎么能证明一个方法永远不会在C#(契约式设计)返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个永远不会返回空对象的方法。我想讲清楚,使我的API的用户不必写这样的代码:

I have a method which never returns a null object. I want to make it clear so that users of my API don't have to write code like this:

if(Getxyz() != null)
{
  // do stuff
}

我怎样才能显示这个意图是什么?

How can I show this intent?

推荐答案

Unforutnately没有办法内置到C#

Unforutnately there is no way built in to C#

您可以记录这个事实,但这将不会被自动检查。

You can document this fact, but this won't be automatically checked.

如果您使用的是ReSharper的,那么就可以设置检查这个当正确方法标有[NOTNULL]属性。

If you are using resharper, then it can be set up to check this properly when the method is marked with a [NotNull] attribute.

否则,您可以使用的微软合同库并添加类似于以下到你的方法什么的,但是这是这样一个简单的注解了不少额外的冗词。

Otherwise you can use the Microsoft Contracts library and add something similar to the following to your method, but this is quite a lot of extra verbiage for such a simple annotation.

Contract.Ensures(Contract.Result<string>() != null)

规格#通过允许解决了这个问题!该类型之后将其标记为一个非空类型,例如:

Spec# solved this problem by allowing a ! after the type to mark it as a non-null type, eg

string! foo



但规格#只能用于靶向.NET2,并由代码契约已经篡库。

but Spec# can only be used to target .NET2, and has been usurped by the Code Contracts library.

这篇关于我怎么能证明一个方法永远不会在C#(契约式设计)返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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