比较两个相同类型的对象返回false

时间:2015-03-24 12:15:22

标签: c# asp.net list

我有两个类 lin

的列表
public class lin
        {
            public string DB_Name;
            public string Object_Name;
        }
List<lin> lines1 = new List<lin>();
List<lin> lines2 = new List<lin>();

我已为这两个列表分配了一些值 下面是立即窗口中索引5处的lines1的输出,其中包含DB_Name = "aesdb_s1"Object_Name = "tblAsiAliasItem"

 lines1[5] 
        DB_Name: "aesdb_s1"
        Object_Name: "tblAsiAliasItem"

索引0处的lines2(zeero)也具有相同的值

lines2[0]
    DB_Name: "aesdb_s1"
    Object_Name: "tblAsiAliasItem"

但是当我比较这两个对象或尝试获取值的索引时,它返回false

lines1.IndexOf(lines2[0])
-1

lines1.Contains(lines2[0]);
false

lines1[5]==lines2[0]
false

这是即时窗口的输出 我不知道为什么会发生这种情况,因为这两个对象具有相同的值和类型,但它返回为false

3 个答案:

答案 0 :(得分:3)

这里的lin可以像你期望的那样工作:

public class Lin : IEquatable<Lin>
{
    public string DbName {get;set;}
    public string ObjectName {get;set;}

    public override bool Equals(object obj) {
        return Equals(obj as Lin);
    }
    public bool Equals(Lin other) {
        return other != null
           && this.DbName == other.DbName
           && this.ObjectName == other.ObjectName;
    }
    public override int GetHashCode() {
        int x = DbName == null ? 0 : DbName.GetHashCode();
        int y = ObjectName == null ? 0 : ObjectName.GetHashCode();
        return (-1423 * x) ^ y;
    }
}

答案 1 :(得分:2)

您正在通过引用比较对象。不值得......

https://msdn.microsoft.com/en-us/library/dd183752.aspx

如果您想比较它们,则需要lin类中的override the Equals()方法专门比较每个属性。

答案 2 :(得分:0)

即使对于==

,这也会为您提供完整的解决方案
 public class lin : IEquatable<lin>
        {
            public string DB_Name;
            public string Object_Name;

            public bool Equals(lin other)
            {
                if (ReferenceEquals(null, other)) return false;
                if (ReferenceEquals(this, other)) return true;
                return string.Equals(DB_Name, other.DB_Name) && string.Equals(Object_Name, other.Object_Name);
            }

            public override bool Equals(object obj)
            {
                if (ReferenceEquals(null, obj)) return false;
                if (ReferenceEquals(this, obj)) return true;
                if (obj.GetType() != this.GetType()) return false;
                return Equals((lin) obj);
            }

            public override int GetHashCode()
            {
                unchecked { return ((DB_Name != null ? DB_Name.GetHashCode() : 0)*397) ^ (Object_Name != null ? Object_Name.GetHashCode() : 0); }
            }

            public static bool operator ==(lin left, lin right)
            {
                return Equals(left, right);
            }

            public static bool operator !=(lin left, lin right)
            {
                return !Equals(left, right);
            }
        }