用户定义的结构不会继承重载的 == 运算符吗?

发布于 2024-11-06 11:06:48 字数 353 浏览 2 评论 0原文

如果引用类型没有重载相等运算符 ==,则将使用 Object 上的内置相等运算符。为什么用户定义的 structs 的情况不同:

struct A{ }

static void Main(string[] args)
{
    A a = new A();
    A a1 = new A();
    bool equal= (a == a1); //error
} 

也就是说,ValueType(所有 structs 均从中派生)也不会重载 < code>== 运算符?

If reference type doesn't overload an equality operator ==, then build-in equality operator on Object will be used instead. Why isn't the same true for user-defined structs:

struct A{ }

static void Main(string[] args)
{
    A a = new A();
    A a1 = new A();
    bool equal= (a == a1); //error
} 

Namely, doesn't ValueType ( from which all structs derive ) also overload == operator?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

冷弦 2024-11-13 11:06:48

这样的默认 == 运算符如何工作?对于引用类型,比较地址是合理的,但由于该检查对于两个 ValueType 永远不会为真(因为如果两个 ValueType 在范围内,则保证它们在堆栈上具有不同的位置),地址比较是没有意义的。

正如编译器所指出的那样,ValueType 故意没有默认的 == 运算符。

How would such a default == operator work? For reference types, comparing adresses is reasonable, but since that check will never be true for two ValueTypes (since if two ValueTypes are in scope then they are guaranteed to have different locations on the stack,) address comparison is pointless.

As the compiler has helpfully pointed out, ValueType very intentionally does not have a default == operator.

醉态萌生 2024-11-13 11:06:48

结构可能不提供默认的 == 运算符实现,因为与类实例不同,结构没有引用样式标识的概念。

来自指南

实现相等运算符
(==) 关于值类型

在大多数编程语言中都有
没有默认实现
值的相等运算符 (==)
类型。因此,你应该超载
==任何时候平等都是有意义的。

您应该考虑实施
值类型上的 equals 方法,因为
默认实现
System.ValueType 将不会执行
以及您的自定义实现。

每当你覆盖
等于方法。

但是,结构do提供了默认的EqualsMethod实现,它将执行使用反射进行成员比较。

Structs probably don't provide a default == operator implementation because, unlike a class instance, a struct has no concept of reference-style identity.

From the guidelines:

Implementing the Equality Operator
(==) on Value Types

In most programming languages there is
no default implementation of the
equality operator (==) for value
types. Therefore, you should overload
== any time equality is meaningful.

You should consider implementing the
Equals method on value types because
the default implementation on
System.ValueType will not perform as
well as your custom implementation.

Implement == any time you override the
Equals method.

However, structs do provide a default Equals Method implementation which will do a memberwise compare using reflection.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文