在为自定义 NUnit 约束编写此方法时。
private void AddMatchFailure<TExpected, TActual>(string failureName, TExpected expected, TActual actual)
{
_matchFailures.Add(
String.Format(MatchFailureFormat, failureName,
(expected == null) ? "null" : expected.ToString(),
(actual == null) ? "null" : actual.ToString()));
}
Resharper 警告 expected
和 actual
可能是 ValueType
对象。
e.g. TExpected is DateTime expected == null;// but DateTime is a struct.
将 ValueType 与 null 进行比较时的规则是什么?我应该如何编写方法来解决这个问题而不通过添加类约束来限制通用参数?
最佳答案
不要更改代码 - 只需忽略警告即可。如果类型参数是不可为 null 的值类型,则比较总是会失败,并且它总是会调用 ToString()
。我不知道它是否真的被 JITted 掉了,但我不会感到惊讶......而且这听起来不像是性能关键代码:)
我个人会将警告保留为“打开”,但在这种特殊情况下忽略它 - 可能带有评论。
我想我在重新实现 LINQ to Objects 时遇到过几次相同的警告。
关于c# - "Possible compare of value type with ' null'”怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5340817/