通过==比较两个结构 [英] compare two structs via ==

查看:77
本文介绍了通过==比较两个结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望通过==比较两个结构,但它不能编译。我可以

重载并创建我自己的==但是我错过了一些c#

已经实现了吗?


~titan

I wish to compare two structs via == but it does not compile. I can
overload and create my own == but am I missing something that c#
already has implemented?

~titan

推荐答案

不,你没有。如果你重载==,那么你必须超载!= as

well。


除此之外,你还应该重载Equals和GetHashCode

产生一致的结果。

-

- Nicholas Paldino [.NET / C#MVP]

- mv*@spam.guard.caspershouse.com

" titan nyquist" < ti *********** @ gmail.com写信息

新闻:11 ******************* ***@z28g2000prd.googlegr oups.com ...
No, you have not. If you overload ==, then you have to overload != as
well.

On top of that, you should also overload Equals and GetHashCode as well
to produce consistent results.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"titan nyquist" <ti***********@gmail.comwrote in message
news:11**********************@z28g2000prd.googlegr oups.com...

>我希望通过==比较两个结构,但它不能编译。我可以

重载并创建我自己的==但是我错过了一些c#

已经实现了吗?


~titan
>I wish to compare two structs via == but it does not compile. I can
overload and create my own == but am I missing something that c#
already has implemented?

~titan



titan nyquist写道:
titan nyquist wrote:

我想比较两个结构==但它不编译。我可以

重载并创建我自己的==但是我错过了一些c#

已经实现了吗?
I wish to compare two structs via == but it does not compile. I can
overload and create my own == but am I missing something that c#
already has implemented?



结构没有默认的比较器,因为比较这些值作为一个二进制数据块并不总是有意义的。


如果你有一个结构:


public struct MyStruct {

private string _name;

public MyStruct(string name){_ name = name; } $ / $
public string Name {get {return _name; } $

}


如果然后创建两个包含相同字符串值的结构值:


MyStruct v1 = new MyStruct(1);

MyStruct v2 = new MyStruct(1.ToString());


如果可以比较这些结构作为二进制数据块的值,它们将不等于
,因为结构包含两个不同的引用,

尽管引用指向相等的字符串值。


-

G?跑Andersson

_____
http://www.guffa.com


" G?ran Andersson" < gu *** @ guffa.comha scritto nel messaggio

新闻:O7 ************** @ TK2MSFTNGP06.phx.gbl ...
"G?ran Andersson" <gu***@guffa.comha scritto nel messaggio
news:O7**************@TK2MSFTNGP06.phx.gbl...

>

没有结构的默认比较器,因为将这些值作为

二进制数据块进行比较总是有意义的。
>
There is no default comparer for structs, as comparing the values as a
binary block of data doesn''t always make sense.



但为什么我能做到这一点?


点p1 =新点(1, 2);


点p2 =新点(1,2);


Console.WriteLine(p1 == p2);


But why I can do this?

Point p1 = new Point(1, 2);

Point p2 = new Point(1, 2);

Console.WriteLine(p1 == p2);



这篇关于通过==比较两个结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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