在 C#/.NET 中将参数标记为不可为空? [英] Mark parameters as NOT nullable in C#/.NET?
问题描述
是否有一个简单的属性或数据协定可以分配给函数参数,以防止在 C#/.NET 中传递 null
?理想情况下,这也会在编译时检查以确保文字 null
没有在任何地方使用它,并在运行时抛出 ArgumentNullException
.
Is there a simple attribute or data contract that I can assign to a function parameter that prevents null
from being passed in C#/.NET? Ideally this would also check at compile time to make sure the literal null
isn't being used anywhere for it and at run-time throw ArgumentNullException
.
目前我写的东西像......
Currently I write something like ...
if (null == arg)
throw new ArgumentNullException("arg");
...对于我希望不是 null
的每个参数.
... for every argument that I expect to not be null
.
同样,是否存在与 Nullable<>
相反的情况,从而导致以下失败:
On the same note, is there an opposite to Nullable<>
whereby the following would fail:
NonNullable<string> s = null; // throw some kind of exception
推荐答案
遗憾的是,编译时没有可用的东西.
There's nothing available at compile-time, unfortunately.
我有点hacky 解决方案,我最近发布在我的博客上,它使用了新的结构和转换.
I have a bit of a hacky solution which I posted on my blog recently, which uses a new struct and conversions.
在带有代码契约的 .NET 4.0 中,生活会好很多.拥有实际的语言语法并支持非可空性仍然会很好,但代码契约将有很大帮助.
In .NET 4.0 with the Code Contracts stuff, life will be a lot nicer. It would still be quite nice to have actual language syntax and support around non-nullability, but the code contracts will help a lot.
我在 MiscUtil 中还有一个名为 ThrowIfNull 的扩展方法,这使得它更简单一些.
I also have an extension method in MiscUtil called ThrowIfNull which makes it a bit simpler.
最后一点 - 有什么理由使用if (null == arg)
"而不是if (arg == null)
"?我发现后者更容易阅读,前者在 C 中解决的问题不适用于 C#.
One final point - any reason for using "if (null == arg)
" instead of "if (arg == null)
"? I find the latter easier to read, and the problem the former solves in C doesn't apply to C#.
这篇关于在 C#/.NET 中将参数标记为不可为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!