C#指定方法参数不可为空

时间:2022-05-27 00:23:51

How would I go about specifying that a particular parameter of my method is not nullable without putting in my own exceptions within the method itself?

如果不在方法本身中放入我自己的异常,我将如何指定我的方法的特定参数不可为空?

Is there something like,

有没有像,

public void Foo (String myRequiredString nullable){

}

5 个解决方案

#1


You can't, basically. You could perhaps use AOP (such as PostSharp) to do some of it for you via attributes, or code-contracts in 4.0 (allowing compile-time checks); but there is no "non-nullable reference-type" (to compare to the "nullable value-type" etc). Not least: what would fields initialize to? and what would default(...) be?

基本上你不能。你也许可以使用AOP(比如PostSharp)通过属性或4.0中的代码契约(允许编译时检查)为你做一些事情;但是没有“不可空的引用类型”(比较“可空值类型”等)。尤其是:字段初始化为什么?默认(...)是什么?

There have been requests to include something in the langauge to help (essentially doing the null check for you), but it hasn't happened. Something like:

有人要求在语言中包含一些内容以帮助(基本上对你进行空检查),但它没有发生。就像是:

public void Foo (string! myRequiredString nullable) {...}

#2


Nothing built in, but you could look at the concept of "design by contract", as implemented in (for example) LinFu.

没有内置,但你可以看看“合同设计”的概念,如(例如)LinFu中所实现的。

#3


In C# 4.0 you can use Code Contracts: InfoQ: .NET 4 Feature Focus: Code Contracts.

在C#4.0中,您可以使用代码约定:InfoQ:.NET 4 Feature Focus:Code Contracts。

All other solutions at the moment involves runtime code checks. You can use an AOP framework, like PostSharp to inject the code into the method, but it all comes down to code in the method.

目前所有其他解决方案都涉及运行时代码检查。您可以使用AOP框架(如PostSharp)将代码注入到方法中,但这一切都归结为方法中的代码。

#4


Aside from getting into some beta version of .NET... which, while exciting, is risky and doesn't really answer your question.

除了进入.NET的一些测试版之外......虽然令人兴奋,但风险很大,并没有真正回答你的问题。

For now unfortunately the best thing you can do is add Intellisense comments to your code that warn not to pass nulls.

现在不幸的是,您可以做的最好的事情是将Intellisense注释添加到您的代码中,警告不要传递空值。

    /// <summary>
    /// This Foo method does Bar to something.
    /// </summary>
    /// <param name="myRequiredString">required, do NOT pass nulls. I really really mean it!</param>
    public void Foo(String myRequiredString)
    {
        if (myRequiredString == null)
        {
            throw new ArgumentNullException("myRequiredString", "It said required in the name of the argument, dummy!");
        }
    }

There are a few hackish solutions out there where people have implemented a generic NonNullable struct, but the bottom line is what you want is for the Visual Studio to not let you type "Foo(null)" and to warn you if you do or give you some compiler error, and the fact is for 99.99% of method calls where something shouldn't be nullable, you're going to have to do the == null check and throw an ArgumentNullException anyhow, because you don't know that the argument is null until runtime. Even if there was what your looking for in C# at the very least the compiler will have to add the null check and throw ArgumentNullException in there.

有一些hackish解决方案,人们已经实现了一个通用的NonNullable结构,但底线是你想要的Visual Studio不要让你键入“Foo(null)”并警告你,如果你这样做或给予你有一些编译器错误,事实是99.99%的方法调用,其中某些东西不应该是可空的,你将不得不进行== null检查并抛出一个ArgumentNullException,因为你不知道参数在运行时为空。即使你在C#中找到了什么,至少编译器必须添加null检查并在那里抛出ArgumentNullException。

I guess I'm saying is what you're looking for is "syntactic sugar" to save your fingers some movement. For now if you're sick of typing that I'd recommend creating a Code Snippet.

我想我说的就是你要找的是“语法糖”来保存你的手指一些动作。现在,如果您厌倦了键入,我建议您创建一个代码段。

#5


I'm currently working on this topic in C#. .NET has Nullable<T> for value types, but the inverse feature doesn't exist for reference types.

我目前正在C#中研究这个主题。对于值类型,.NET具有Nullable ,但引用类型不存在反向特征。

I created NotNullable<T> for reference types, and moved the problem from if's (no more checks for null) to the datatype domain. However, this makes the application to throw exceptions in runtime and not in compile-time, but it's still very useful for me.

我为引用类型创建了NotNullable ,并将问题从if(不再检查null)移动到数据类型域。但是,这使得应用程序在运行时而不是在编译时抛出异常,但它对我来说仍然非常有用。

#1


You can't, basically. You could perhaps use AOP (such as PostSharp) to do some of it for you via attributes, or code-contracts in 4.0 (allowing compile-time checks); but there is no "non-nullable reference-type" (to compare to the "nullable value-type" etc). Not least: what would fields initialize to? and what would default(...) be?

基本上你不能。你也许可以使用AOP(比如PostSharp)通过属性或4.0中的代码契约(允许编译时检查)为你做一些事情;但是没有“不可空的引用类型”(比较“可空值类型”等)。尤其是:字段初始化为什么?默认(...)是什么?

There have been requests to include something in the langauge to help (essentially doing the null check for you), but it hasn't happened. Something like:

有人要求在语言中包含一些内容以帮助(基本上对你进行空检查),但它没有发生。就像是:

public void Foo (string! myRequiredString nullable) {...}

#2


Nothing built in, but you could look at the concept of "design by contract", as implemented in (for example) LinFu.

没有内置,但你可以看看“合同设计”的概念,如(例如)LinFu中所实现的。

#3


In C# 4.0 you can use Code Contracts: InfoQ: .NET 4 Feature Focus: Code Contracts.

在C#4.0中,您可以使用代码约定:InfoQ:.NET 4 Feature Focus:Code Contracts。

All other solutions at the moment involves runtime code checks. You can use an AOP framework, like PostSharp to inject the code into the method, but it all comes down to code in the method.

目前所有其他解决方案都涉及运行时代码检查。您可以使用AOP框架(如PostSharp)将代码注入到方法中,但这一切都归结为方法中的代码。

#4


Aside from getting into some beta version of .NET... which, while exciting, is risky and doesn't really answer your question.

除了进入.NET的一些测试版之外......虽然令人兴奋,但风险很大,并没有真正回答你的问题。

For now unfortunately the best thing you can do is add Intellisense comments to your code that warn not to pass nulls.

现在不幸的是,您可以做的最好的事情是将Intellisense注释添加到您的代码中,警告不要传递空值。

    /// <summary>
    /// This Foo method does Bar to something.
    /// </summary>
    /// <param name="myRequiredString">required, do NOT pass nulls. I really really mean it!</param>
    public void Foo(String myRequiredString)
    {
        if (myRequiredString == null)
        {
            throw new ArgumentNullException("myRequiredString", "It said required in the name of the argument, dummy!");
        }
    }

There are a few hackish solutions out there where people have implemented a generic NonNullable struct, but the bottom line is what you want is for the Visual Studio to not let you type "Foo(null)" and to warn you if you do or give you some compiler error, and the fact is for 99.99% of method calls where something shouldn't be nullable, you're going to have to do the == null check and throw an ArgumentNullException anyhow, because you don't know that the argument is null until runtime. Even if there was what your looking for in C# at the very least the compiler will have to add the null check and throw ArgumentNullException in there.

有一些hackish解决方案,人们已经实现了一个通用的NonNullable结构,但底线是你想要的Visual Studio不要让你键入“Foo(null)”并警告你,如果你这样做或给予你有一些编译器错误,事实是99.99%的方法调用,其中某些东西不应该是可空的,你将不得不进行== null检查并抛出一个ArgumentNullException,因为你不知道参数在运行时为空。即使你在C#中找到了什么,至少编译器必须添加null检查并在那里抛出ArgumentNullException。

I guess I'm saying is what you're looking for is "syntactic sugar" to save your fingers some movement. For now if you're sick of typing that I'd recommend creating a Code Snippet.

我想我说的就是你要找的是“语法糖”来保存你的手指一些动作。现在,如果您厌倦了键入,我建议您创建一个代码段。

#5


I'm currently working on this topic in C#. .NET has Nullable<T> for value types, but the inverse feature doesn't exist for reference types.

我目前正在C#中研究这个主题。对于值类型,.NET具有Nullable ,但引用类型不存在反向特征。

I created NotNullable<T> for reference types, and moved the problem from if's (no more checks for null) to the datatype domain. However, this makes the application to throw exceptions in runtime and not in compile-time, but it's still very useful for me.

我为引用类型创建了NotNullable ,并将问题从if(不再检查null)移动到数据类型域。但是,这使得应用程序在运行时而不是在编译时抛出异常,但它对我来说仍然非常有用。