【发布时间】:2013-10-31 22:28:21
【问题描述】:
我想让程序员和我自己知道一个方法不需要null,如果你还是发送null给它,结果不会很漂亮。
Lokad Shared Libraries 中有一个 NotNullAttribute 和一个 CanBeNullAttribute,在 Lokad.Quality 命名空间中。
但它是如何工作的?我查看了这两个属性的源代码,它看起来像这样:
[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-documentation 并知道它在那里?因为我尝试制作自己的属性副本并使用 Lokad 版本,但是当我尝试直接发送空值时,我没有收到任何消息。既不是来自 ReSharper 也不是来自 VS。实际上,我有点期待。但是它们是如何使用的呢?如果我尝试在其中发送 null 的内容,我能否以某种方式让 VS 为我生成警告?还是只是在某种测试框架中使用?还是?
【问题讨论】:
-
要评论您的具体案例,这些属性不做任何事情,只是“文档”。不过,其他答案提供了很好的选择。
-
Nullable是CanBeNull的更好名称,只是说:)
标签: c# attributes null