不要用户定义的结构继承一个重载的==操作符? [英] Don't user-defined structs inherit an overloaded == operator?

查看:139
本文介绍了不要用户定义的结构继承一个重载的==操作符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果引用类型不超载相等运算符 == ,然后建立的相等操作符的对象将被用来代替。为什么为是不一样的真正的用户自定义的结构

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?

推荐答案

怎么会出现这样的默认的==操作符的工作?对于引用类型,比较不会忽略是合理的,但由于查收永远不会真正的两个值类型(因为如果两个值类型的范围,然后,他们都保证有堆栈上的不同位置,)地址比较是没有意义的。

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.

这篇关于不要用户定义的结构继承一个重载的==操作符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆