用户定义的结构不会继承重载的 == 运算符吗?
如果引用类型没有重载相等运算符 ==
,则将使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这样的默认 == 运算符如何工作?对于引用类型,比较地址是合理的,但由于该检查对于两个 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.
结构可能不提供默认的 == 运算符实现,因为与类实例不同,结构没有引用样式标识的概念。
来自指南:
但是,结构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:
However, structs do provide a default Equals Method implementation which will do a memberwise compare using reflection.