为什么C#不相互比较两个对象类型,但VB不? [英] Why C# fails to compare two object types with each other but VB doesn't?
问题描述
我在C#中的两个对象,不知道这是否是布尔或任何其他类型。 然而,当我试图比较这些C#未能得到正确的答案。 我曾尝试在同一code用VB.NET并做到了!
谁能告诉我如何解决这个问题,如果有一个解决方案?
C#:
对象= TRUE;
对象B = TRUE;
对象C = FALSE;
若(a == B)C =真;
的MessageBox.show(c.ToString()); //输出假!
VB.NET:
暗淡了为对象真=
昏暗b以对象=真
尺寸C为对象=假
如果(A = B),则C =真
的MessageBox.show(c.ToString())//输出true
在C#中, ==
操作符(当应用于引用类型EX pressions)执行一个的引用的平等检查,除非它的重载。你比较两个引用这是装箱转换的结果,所以这些都是不同的参考。
编辑:随着它超载类型==
,就可以得到不同的行为 - 但是这基础上的编译时间的类型EX pressions。例如,字符串
为 ==(字符串,字符串
):
字符串x =新的字符串(富.ToCharArray());
字符串Y =新的字符串(富.ToCharArray());
Console.WriteLine(x == y)的; // 真正
Console.WriteLine((对象)x ==(对象)Y); // 假
下面的第一个比较使用重载运算符,但第二个是使用默认的参考比较。
在VB中, =
运营商做了很多更多的工作 - 它甚至不是仅仅等同于使用的Object.Equals(X,Y)
,象外之象 选项比较
可能会影响文本进行比较。
从根本上对经营者不相同的方式工作,并且不的意的工作方式相同。
I have two objects in C# and don't know if it's Boolean or any other type. However when I try to compare those C# fails to give the right answer. I have tried the same code with VB.NET and that did it !
Can anyone tell me how to fix this if there is a solution ?
C#:
object a = true;
object b = true;
object c = false;
if (a == b) c = true;
MessageBox.Show(c.ToString()); //Outputs False !!
VB.NET:
Dim a As Object = True
Dim b As Object = True
Dim c As Object = False
If (a = b) Then c = True
MessageBox.Show(c.ToString()) '// Outputs True
In C#, the ==
operator (when applied to reference type expressions) performs a reference equality check unless it's overloaded. You're comparing two references which are the result of boxing conversions, so those are distinct references.
EDIT: With types which overload the ==
, you can get different behaviour - but that's based on the compile-time type of the expressions. For example, string
provides ==(string, string
):
string x = new string("foo".ToCharArray());
string y = new string("foo".ToCharArray());
Console.WriteLine(x == y); // True
Console.WriteLine((object) x == (object) y); // False
Here the first comparison is using the overloaded operator, but the second is using the "default" reference comparison.
In VB, the =
operator does a whole lot more work - it's not even just equivalent to using object.Equals(x, y)
, as things like Option Compare
can affect how text is compared.
Fundamentally the operators don't work the same way and aren't intended to work the same way.
这篇关于为什么C#不相互比较两个对象类型,但VB不?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!