Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

C#: How to Implement and use a NotNull and CanBeNull attribute

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.

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

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
{
}

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?

question from:https://stackoverflow.com/questions/792531/c-how-to-implement-and-use-a-notnull-and-canbenull-attribute

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

(edit) example:

Contract.RequiresAlways( x != null );

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...