马克参数在C#/。NET为不可为空? [英] Mark parameters as NOT nullable in C#/.NET?
问题描述
有一个简单的属性或数据的合同,我可以分配给一个函数参数起价传递在C#/。NET p $ pvents 空
?理想情况下,这也将检查在编译时间,以确保文字空
不被使用的任何地方,并在运行时抛出 ArgumentNullException
。
目前我喜欢写东西......
如果(空== ARG)
抛出新ArgumentNullException(ARG);
......为此,我希望不是每一个参数空
。
在同样的注意,是有一个相对可空<>
由此,以下将失败:
非空<字符串> S = NULL; //抛出某种异常
没有什么可以在编译时,很遗憾。
我有点哈克解决方案我贴在我的博客最近,它采用了新的结构和转换。
在.NET 4.0的 code合同的东西,人生将是要好很多。这仍然是相当不错的,各地的非空性的实际语言的语法和支持,但code合约将有很大的帮助。
我也有一个扩展方法 MiscUtil 称为ThrowIfNull这使得它有点简单。
最后一点 - 任何理由使用如果(空== ARG)
,而不是如果(ARG == NULL)
?我觉得后者更容易阅读,这个问题在C前者解决了并不适用于C#。
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");
... for every argument that I expect to not be null
.
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.
I have a bit of a hacky solution which I posted on my blog recently, which uses a new struct and conversions.
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.
I also have an extension method in MiscUtil called ThrowIfNull which makes it a bit simpler.
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屋!