如何在代码中使用.Equals [英] How to use .Equals in the code
本文介绍了如何在代码中使用.Equals的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以使用以下代码行说不等于
Hi,
Can I use the following line of code for saying not equal to
if (!(CANMsgIdList[f].Bus).Equals(ConsoleApplication13.Buses.CANBusGreen)
< br $>
谢谢
John
Thanks
John
推荐答案
是的。
因为您的Buses
是一个枚举
,它也可以正常工作,它将是一个值比较而不是引用。如果Buses
是一个类,那么它可能无法准确给出您的预期。
Yes.
Because yourBuses
is anenum
, it will also work fine, and it will be a value comparison rather than a reference. IfBuses
was a class, then it might not give exactly what you expected.
如果使用.Equals将类的实例与枚举值进行比较:它将始终评估为'false。我认为VS 2013 C#编译器将允许这样的比较进行编译而不使用警告是一个缺陷(如果你使用ReSharper,ReSharper会发出警告)。
正如Karthik所示(上图)你可以比较th的值e使用标准相等运算符直接使用相同的枚举类型==或!=
如果类的实例具有Field或属性,其类型为一个特定的枚举类型,当然你可以将它与同一类型的枚举值进行比较;如果一个方法返回一个枚举值,你可以与之比较。
如果你想比较枚举值你可以使用.Equals:
If you compare an instance of a Class with an Enum Value using .Equals: it will always evaluate to 'false. I think the fact that the VS 2013 C# compiler will allow such a comparison to compile without a warning is a flaw (if you are using ReSharper, ReSharper will put up a warning).
As Karthik demonstrated (above) you can compare Values of the same Enum Type directly using the standard equality operators "==" or "!="
If an instance of a Class has a Field, or Property whose Type is a specific Enum Type, of course you can compare that with an Enum Value of the same Type; if a method returns an Enum Value, you can compare with that.
You can use .Equals if you wish to compare Enum Values:
bool testEquals = SomeClassInstance.TheBus.Equals(Buses.green);
有效。但是,为什么在使用普通的相等运算符更简单时使用呢?
Is valid. But, why use that when it's simpler to just use the ordinary equality operators ?
是的你可以使用它..
简单的方法是
Yes u can use it..
simple way is
if ((CANMsgIdList[f].Bus)!=(ConsoleApplication13.Buses.CANBusGreen))
看看这个
c-sharp-difference-between-and-equals [ ^ ]
这篇关于如何在代码中使用.Equals的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文