問題描述
我想讓程序員和我自己知道一個方法不需要 null
并且如果你確實發送 null
給它,結果不會很漂亮.
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.
Lokad 中有一個 NotNullAttribute
和一個 CanBeNullAttribute
共享庫,位于 Lokad.Quality
命名空間中.
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
{
}
從 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?
推薦答案
在中期,代碼契約"(在 4.0 中)將是一個更好的答案.它們現在可用(通過 academic 或 商業 許可證),但將在 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 );
就這么簡單……代碼契約引擎在 IL 級別工作,因此它可以分析并在構建期間或運行時調用代碼時拋出警告/錯誤.為了向后兼容,如果您有現有的驗證代碼,您只需告訴它健全性檢查在哪里結束,剩下的就交給它了:
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 屬性的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!