首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么C#不能比较两种对象类型,而VB不能?

为什么C#不能比较两种对象类型,而VB不能?
EN

Stack Overflow用户
提问于 2013-02-13 00:31:43
回答 1查看 6.4K关注 0票数 152

我在C#中有两个对象,不知道它是布尔型的还是其他类型的。然而,当我尝试比较它们时,C#没有给出正确的答案。我已经用VB.NET尝试了相同的代码,并且成功了!

如果有解决方案,谁能告诉我如何解决这个问题?

C#:

代码语言:javascript
复制
object a = true;
object b = true;
object c = false;
if (a == b) c = true;
MessageBox.Show(c.ToString()); //Outputs False !!

VB.NET:

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2013-02-13 00:40:16

对象实例不与运算符"==“进行比较。你应该使用"equals“方法。与"==“运算符比较的是引用,而不是对象。

试试这个:

代码语言:javascript
复制
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");
}

结果:

代码语言:javascript
复制
a reference is not equal to b reference
a object is not equal to b object

现在,试试这个:

代码语言:javascript
复制
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");
}

结果:

代码语言:javascript
复制
a reference is not equal to b reference
a object is equal to b object
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14837209

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档