中泛型参数的空值或默认比较

中泛型参数的空值或默认比较

本文介绍了C# 中泛型参数的空值或默认比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样定义的通用方法:

I have a generic method defined like this:

public void MyMethod<T>(T myArgument)

我想做的第一件事是检查 myArgument 的值是否是该类型的默认值,如下所示:

The first thing I want to do is check if the value of myArgument is the default value for that type, something like this:

if (myArgument == default(T))

但这不能编译,因为我不能保证 T 会实现 == 操作符.所以我把代码改成这样:

But this doesn't compile because I haven't guaranteed that T will implement the == operator. So I switched the code to this:

if (myArgument.Equals(default(T)))

现在可以编译了,但是如果 myArgument 为 null(这是我正在测试的内容的一部分),则会失败.我可以像这样添加一个显式的空检查:

Now this compiles, but will fail if myArgument is null, which is part of what I'm testing for. I can add an explicit null check like this:

if (myArgument == null || myArgument.Equals(default(T)))

现在这对我来说是多余的.ReSharper 甚至建议我将 myArgument == null 部分更改为 myArgument == default(T) ,这是我开始的地方.有没有更好的方法来解决这个问题?

Now this feels redundant to me. ReSharper is even suggesting that I change the myArgument == null part into myArgument == default(T) which is where I started. Is there a better way to solve this problem?

我需要同时支持引用类型和值类型.

I need to support both references types and value types.

推荐答案

为了避免装箱,比较泛型是否相等的最好方法是使用 EqualityComparer.Default.这尊重 IEquatable(无装箱)以及 object.Equals,并处理所有 Nullable提升"的细微差别.因此:

To avoid boxing, the best way to compare generics for equality is with EqualityComparer<T>.Default. This respects IEquatable<T> (without boxing) as well as object.Equals, and handles all the Nullable<T> "lifted" nuances. Hence:

if(EqualityComparer<T>.Default.Equals(obj, default(T))) {
    return obj;
}

这将匹配:

  • 类为空
  • null(空)用于 Nullable
  • 其他结构的零/假/等

这篇关于C# 中泛型参数的空值或默认比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 10:02