C#中:如何实施和使用NOTNULL和CanBeNull属性 [英] C#: How to Implement and use a NotNull and CanBeNull attribute

查看:4461
本文介绍了C#中:如何实施和使用NOTNULL和CanBeNull属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要让程序员和我知道的方法不希望键,如果你发送它反正,结果不会是pretty。

I want to let programmers and myself know that a method does not want null and if you do send null to it anyways, the result will not be pretty.

有一个 NotNullAttribute CanBeNullAttribute 中的 Lokad共享库,在 Lokad.Quality 命名空间。

There is a NotNullAttribute and a CanBeNullAttribute in Lokad Shared Libraries, in the Lokad.Quality namespace.

但如何运作的?我看着这两个属性的源 - code,它看起来是这样的:

But how does that work? I looked at the source-code of those two attributes, and it looks like this:

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter |
                AttributeTargets.Property | AttributeTargets.Delegate |
                AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
[NoCodeCoverage]
public sealed class NotNullAttribute : Attribute
{
}

[AttributeUsage(AttributeTargets.Method | AttributeTargets.Parameter |
                AttributeTargets.Property | AttributeTargets.Delegate |
                AttributeTargets.Field, AllowMultiple = false, Inherited = true)]
[NoCodeCoverage]
public sealed class CanBeNullAttribute : Attribute
{
}

两空类从属性继承。他们如何使用?你要回去看看XML的文档,并且知道它的存在?因为我想既让我自己属性的副本,并使用Lokad的版本,但是当我试图直接发送一个空,我没有得到消息。无论是从ReSharper的也不是来自VS.我居然有种期待。但是,如何使用它们?我能以某种方式让VS生成警告我,如果我尝试发送的东西是空在那里?或者只是某种测试框架的使用呢?还是?

Two empty classes inheriting from Attribute. How are they used? Do you have to look up xml-documentation and know that it is there? Cause I tried to both make my own copy of the attribute and to use the Lokad version, but when I tried to send a null directly in, I got no message. Neither from ReSharper nor from VS. Which I kind of expected actually. But how are they used? Can I somehow make VS generate warnings for me if I try to send something that is null in there? Or is it just used in some kind of testing framework? Or?

推荐答案

在中期,code合同(4.0)将是一个更好的答案。他们现在可以(与学术或的商业许可证),反而会更集成在VS2010。这可以提供静态分析和运行时支持。

In the mid-term, "code contracts" (in 4.0) will be a better answer to this. They are available now (with academic or commercial licences), but will be more integrated in VS2010. This can provide both static analysis and runtime support.

(编辑)例如:

Contract.RequiresAlways( x != null );

就这么简单......在code合同发动机工作在IL级别,因此它可以分析和生成过程中调用code抛出警告/错误,或者在运行时。为了向下兼容,如果你现有的验证code,你可以告诉它的健全检查结束后,它会完成剩下的:

Simple as that... the code contracts engine works at the IL level, so it can analyse that and throw warnings/errors from calling code during build, or at runtime. For backwards compatibility, if you have existing validation code, you can just tell it where the sanity checking ends, and it'll do the rest:

if ( x == null ) throw new ArgumentNullException("x");
Contract.EndContractBlock();

这篇关于C#中:如何实施和使用NOTNULL和CanBeNull属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆