我想让程序员和我自己知道一个方法不需要null,如果你确实发送null它,结果将不会很好.
有一个NotNullAttribute和CanBeNullAttribute在Lokad共享库,在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
{
}
Run Code Online (Sandbox Code Playgroud)
继承自的两个空类Attribute.它们是如何使用的?你需要查找xml文档并知道它在那里吗?因为我试图制作我自己的属性副本并使用Lokad版本,但是当我尝试直接发送null时,我没有收到任何消息.既不是来自ReSharper也不是来自VS. 实际上我有点期待.但他们是如何使用的呢?如果我尝试发送一些空的东西,我可以以某种方式让VS为我生成警告吗?或者它只是在某种测试框架中使用?要么?
是的,我知道我会完全看起来像这个白痴,但我的大脑今天早上并没有开始装备.
我想要一个方法,我可以说"如果它变坏了,请回到这种类型的异常",对吧?
例如,类似的东西(这不起作用):
static ExType TestException<ExType>(string message) where ExType:Exception
{
Exception ex1 = new Exception();
ExType ex = new Exception(message);
return ex;
}
Run Code Online (Sandbox Code Playgroud)
现在让我感到困惑的是,我们知道泛型类型由于where子句而属于Exception类型.但是,代码失败是因为我们无法隐式地将Exception 强制转换为ExType.我们也无法明确转换它,例如:
static ExType TestException<ExType>(string message) where ExType:Exception
{
Exception ex1 = new Exception();
ExType ex = (ExType)(new Exception(message));
return ex;
}
Run Code Online (Sandbox Code Playgroud)
因为那也失败了......那么这种事情可能吗?我有一种强烈的感觉,它会变得非常简单,但是我和老头脑一起度过了艰难的一天,所以让我有些松懈:P
感谢回复的人,看起来我不是一个完全白痴!;)
好的,所以Vegard和Sam让我能够实例化正确的类型,但显然卡住了,因为消息参数在实例化后是只读的.
Matt用他的回答击中了正确的指甲,我测试了这一切,一切正常.这是示例代码:
static ExType TestException<ExType>(string message) where ExType:Exception, new …Run Code Online (Sandbox Code Playgroud) .NET Standard不支持静态代码分析和代码契约吗?
VS 2017和.NET Standard 1.6或.NET核心类库似乎没有运行代码分析的选项.