gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:37:07 26 4
gpt4 key购买 nike

根据 == 的文档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/31470339/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com