按契约/C# 4.0/避免 ArgumentNullException 进行设计
我非常厌倦检查所有参数是否为空,并在它们为空时抛出 ArgumenutNullExceptions。
据我了解,C# 4.0 通过契约构造实现了一些设计。 在 C# 4.0 中是否可以指定一个方法不接受 null 参数?
另外,同时我可以做些什么(也许是一个属性?)来避免这种检查 null 和抛出的单调任务?
I'm terribly tired of checking all my arguments for null, and throwing ArgumenutNullExceptions when they are.
As I understand it, C# 4.0 enables some design by contract constructs. Will it be possible to specify that a method will not accept null arguments in C# 4.0?
Also, is there anything I can do in the meantime (maybe an attribute?) to avoid this monotonous task of checking for null and throwing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以创建一个
NotNull
泛型类来提供帮助,但也有一些副作用。 请参阅 Robert Nystrom 的博文。You can create a
NotNull<T>
generic class that helps, but there are some side effects. See Robert Nystrom's blog post.Rick Brewster 在这篇文章中描述了一个用于简洁、声明式样式参数检查的良好解决方案,
http://blog.getpaint.net/2008/12/06/a- Fluent-approach-to-c-parameter-validation/
避免使用反射(缺点DbC)并且不会为非异常代码路径产生任何开销。
就像他如何使用扩展方法来允许对空对象进行看似实例方法的调用。 在我看来,编码非常聪明。
如果您热衷于 DbC、Google Spec# 和 PostSharp。
Rick Brewster describes a good solution for concise, declarative style parameter checking in this post,
http://blog.getpaint.net/2008/12/06/a-fluent-approach-to-c-parameter-validation/
Avoids use of reflection (drawback of DbC) and creates no overhead for non-exceptional code path.
Like how he uses extension methods to allow what appears to be instance method calls on null objects. Very clever bit of coding IMO.
If you are sold on DbC, Google Spec# and PostSharp.
不确定 C# 4.0 中的本机 DbC 构造,但 Microsoft 将发布跨语言 合约 库。
您可以此处下载 MSVS2008 版本< /a>.
Not sure about native DbC constructs in C# 4.0 but Microsoft is going to release cross-language Contracts library.
You can download version for MSVS2008 here.
作为已经给出的答案的替代方案,值得研究
空对象设计模式
。这种设计模式的本质是,一旦创建了“空对象”,就不再需要对null及其方法执行任何检查每当传递 null(否则)而不是对“真实对象”的引用时,null 对象就会实现所需的行为。
此设计模式不依赖于 C# 4.0,实际上可以在几乎任何 OO 编程语言中轻松实现。
As an alternative to the already given answers, it is worth looking into the
Null Object design pattern
.The essence of this design pattern is that once the "null object" is created, there is no further need to perform any checks for null and the methods of the null object implement the behavior desired whenever a null (otherwise) would have been passed vs a reference to a "real object".
This design pattern does not depend on C# 4.0 and in fact can be easily implemented in almost any OO programming language.
我刚刚开始使用代码合约,它是 C# 4.0 中的一项新功能,您需要从 MS 下载插件才能在项目设置中看到它。 详情请看这里->
http://research.microsoft.com/en-us/projects/contracts/< /a>
I have just started using Code Contracts its a new feature in C# 4.0 you need to download an addin from MS to allow you to see it in your project settings. Details here ->
http://research.microsoft.com/en-us/projects/contracts/