CA1062:协同构造函数调用上的 ValidateArgumentsOfPublicMethods
我有一个包含两个构造函数的类,如下所示:
public MyClass(SomeOtherClass source) : this(source, source.Name) { }
public MyClass(SomeOtherClass source, string name) { /* ... */ }
当我运行 FxCop 时,它正确报告违反 CA1062: ValidateArgumentsOfPublicMethods,因为如果第一个构造函数中的 source
为 null
,它将在 NullReferenceException
上抛出 NullReferenceException
代码>源.名称。
有什么办法可以解决这个警告吗?
我可以创建一个扩展方法来检查 null 并返回其参数,但它会很难看。 另外,据我了解,它不会解决警告,因为 FxCop 不会意识到它的作用。
I have a class with two constructors that look like this:
public MyClass(SomeOtherClass source) : this(source, source.Name) { }
public MyClass(SomeOtherClass source, string name) { /* ... */ }
When I run FxCop, it correctly reports a violation of CA1062: ValidateArgumentsOfPublicMethods, because if source
is null
in the first constructor, it will throw a NullReferenceException
on source.Name
.
Is there any way to fix this warning?
I could make an extension method that checks for null and returns its argument, but it would be ugly. Also, as I understand, it wouldn't resolve the warning because FxCop wouldn't realize what it does.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
像这样?
Like this?
有合法的时间来关闭 FxCop 警告,这很可能就是一个,但是您可以通过检查 null 并引发异常(或替换默认值)的三元表达式或调用静态来纠正问题检查 null 并抛出适当异常的方法。
There are legitimate times to turn off FxCop warnings and this could very well be one, but you can correct the problem by either a ternary expression that checks for null and throws an exception (or substitutes a default value), or a call to a static method that checks for null and throws the appropriate exception.
由于这个问题是前一段时间提出的,我只想注意 C# 中的后续功能,您现在也可以使用它:
Since this question was asked some time ago I just want to note with the later features in C# you can now also use this:
从 C# 7.0 开始,您还可以执行以下操作:
C# 7.0 允许将异常作为表达式抛出。 (请参阅 Microsoft 文档 )
Since C# 7.0 you can also do this:
C# 7.0 allows throwing exceptions as expressions. (See Microsoft Docs)
我想说解决此警告的唯一方法是将其关闭。 FxCop 是一个很棒的工具,但有时您需要记住它只是一个工具,并且可以提出并不总是适合您的代码的建议。
在此示例中,如果您不想看到它,我会说忽略警告或禁用它。
I would say the only way to fix this warning would be to turn it off. FxCop is a great tool but sometimes you need to remember that it is just a tool and can make suggestions that are not always fitting to your code.
In this example I would say ignore the warning or disable it if you don't want to see it.