简体   繁体   English

C#:声明函数永远不会返回null?

[英]C#: Declare that a function will never return null?

Background: There is this developer principle "Should my function return null or throw an exception if the requested item does not exist?" 背景:有这个开发人员原则“如果请求的项目不存在,我的函数应该返回null还是抛出异常?” that I wouldn't like to discuss here. 我不想在这里讨论。 I decided to throw an exception for all cases that have to return a value and this value only wouldn't exist in cases of an (programmatically or logically) invalid request. 我决定为所有必须返回值的情况抛出异常,并且只有在(编程或逻辑)无效请求的情况下才会存在此值。

And finally my question: Can I mark a function so that the compiler knows that it will never return null and warn anybody who checks if the return value is null? 最后我的问题是:我可以标记一个函数,以便编译器知道它永远不会返回null并警告任何检查返回值是否为空的人?

You can do this using Code Contracts . 您可以使用Code Contracts执行此操作。

Example : 示例:

    public String Method1()
    { 
        Contract.Ensures(Contract.Result<String>() != null);

        // To do
    }

Using Code Contracts you can define a contract that a method does not return null. 使用代码约定,您可以定义方法不返回null的约定。

using System.Diagnostics.Contracts; // required namespace 

public T MethodName()
{
    Contract.Ensures(Contract.Result<T>() != null); //where T is the return type.

    // method body...
}

您正在寻找代码合同

如果返回值类型,则它不能为null(除非您使用系统'nullable'包装器明确地使用它)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM