简体   繁体   中英

CA1062: ValidateArgumentsOfPublicMethods on co-constructor calls

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.

Like this?

public MyClass(SomeOtherClass source) : this(source, source == null ? null : source.Name) { }
public MyClass(SomeOtherClass source, string name) { /* ... */ }

有合法的时间来关闭FxCop警告,这很可能是一个,但您可以通过检查null并抛出异常(或替换默认值)的三元表达式或调用静态来纠正问题检查null并抛出相应异常的方法。

由于前一段时间问过这个问题,我只想注意C#中的后续功能,你现在也可以使用它:

public MyClass(SomeOtherClass source) : this(source, source?.Name) { }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM