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

后端 未结 4 1497
执笔经年
执笔经年 2020-12-08 07:15

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.

4条回答
  •  伪装坚强ぢ
    2020-12-08 07:42

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

提交回复
热议问题