c# - "Possible compare of value type with ' null'”怎么办?

标签 c#

在为自定义 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 警告 expectedactual 可能是 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/

相关文章:

c# - 下面的 C# 代码(链接条件三元运算符)的含义是什么

c# - 获取当前正在运行的应用程序列表,而不是进程 c#

c# - 在 C# 中显示电子邮件正文中的数据表

c# - OrderBy 数字和 ThenBy bool 值不适用于 List

c# - 如何加入两个字典集合linq查询

c# - 如何使用 Math.Round 舍入精确的 double 值

c# - WebClient读取错误页面内容

c# - 在 c# 中使用 SSE 4.2 crc32 算法?是否可以?

c# - 指定接口(interface)只能由引用类型实现 C#

c# - 统一和生命周期管理