我在C#中有两个对象,不知道它是布尔型的还是其他类型的。然而,当我尝试比较它们时,C#没有给出正确的答案。我已经用VB.NET尝试了相同的代码,并且成功了!
如果有解决方案,谁能告诉我如何解决这个问题?
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
发布于 2013-02-13 00:40:16
对象实例不与运算符"==“进行比较。你应该使用"equals“方法。与"==“运算符比较的是引用,而不是对象。
试试这个:
public class MyObject
{
public MyObject(String v)
{
Value = v;
}
public String Value { get; set; }
}
MyObject a = new MyObject("a");
MyObject b = new MyObject("a");
if(a==b){
Debug.WriteLine("a reference is equal to b reference");
}else{
Debug.WriteLine("a reference is not equal to b reference");
}
if (a.Equals(b)) {
Debug.WriteLine("a object is equal to b object");
} else {
Debug.WriteLine("a object is not equal to b object");
}
结果:
a reference is not equal to b reference
a object is not equal to b object
现在,试试这个:
public class MyObject
{
public MyObject(String v)
{
Value = v;
}
public String Value { get; set; }
public bool Equals(MyObject o)
{
return (Value.CompareTo(o.Value)==0);
}
}
MyObject a = new MyObject("a");
MyObject b = new MyObject("a");
if(a==b){
Debug.WriteLine("a reference is equal to b reference");
}else{
Debug.WriteLine("a reference is not equal to b reference");
}
if (a.Equals(b)) {
Debug.WriteLine("a object is equal to b object");
} else {
Debug.WriteLine("a object is not equal to b object");
}
结果:
a reference is not equal to b reference
a object is equal to b object
https://stackoverflow.com/questions/14837209
复制相似问题