c# - 运算符 == 不能应用于 C# 中的泛型类型吗?

标签 c# generics operators equals-operator

根据 == 的文档MSDN 中的运算符,

For predefined value types, the equality operator (==) returns true if the values of its operands are equal, false otherwise. For reference types other than string, == returns true if its two operands refer to the same object. For the string type, == compares the values of the strings. User-defined value types can overload the == operator (see operator). So can user-defined reference types, although by default == behaves as described above for both predefined and user-defined reference types.

那么为什么这段代码会编译失败呢?

bool Compare<T>(T x, T y) { return x == y; }

我收到错误消息Operator '==' cannot be applied to operands of type 'T' and 'T'。我想知道为什么,因为据我所知 ==运算符是为所有类型预定义的?

编辑 谢谢大家。起初我没有注意到该声明仅是关于引用类型的。我还认为为所有值类型提供了逐位比较,我现在知道这是正确的。

但是,如果我使用的是引用类型,== 会吗?运算符使用预定义的引用比较,或者如果类型定义了运算符,它会使用运算符的重载版本吗?

编辑 2:通过反复试验,我们了解到 ==运算符在使用不受限制的泛型类型时将使用预定义的引用比较。实际上,编译器将使用它能为受限类型参数找到的最佳方法,但不会进一步查找。例如,下面的代码将始终打印 true ,即使 Test.test<B>(new B(), new B())被称为:

class A { public static bool operator==(A x, A y) { return true; } }
class B : A { public static bool operator==(B x, B y) { return false; } }
class Test { void test<T>(T a, T b) where T : A { Console.WriteLine(a == b); } }

最佳答案

正如其他人所说,只有当 T 被限制为引用类型时它才会起作用。在没有任何限制的情况下,您可以与 null 进行比较,但只能与 null 进行比较 - 对于不可为 null 的值类型,该比较始终为 false。

与其调用 Equals,不如使用 IComparer<T> 更好- 如果您没有更多信息,EqualityComparer<T>.Default是个不错的选择:

public bool Compare<T>(T x, T y)
{
    return EqualityComparer<T>.Default.Equals(x, y);
}

除此之外,这避免了装箱/转换。

关于c# - 运算符 == 不能应用于 C# 中的泛型类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/390900/

相关文章:

java - 如何按名称实例化参数化类型类

java - 在带有 && 运算符的 if 语句中使用 char 数组和 boolean 数组

c# - 引用类型,StringBuilder

c++ - 如何在 C++ 中使用可变参数泛型 lambda 计算总和?

c# - 有没有办法使用 GPU 调整图像大小?

java - 初始化 ArrayList<Record<T>>[] 值;

php - 2 > 10 在 PHP 中如何成立?

javascript - 如何将逻辑/数学运算符分配给对象的函数?

c# - 如何将 confluent-kafka 与 key 存储文件一起使用

c# - 如何处理数据库中的字典表