c# - 比较两个相同类型的对象在 C# 中返回 false

标签 c# 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>();

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

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

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

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

以上是visual studio的即时窗口输出

最佳答案

这是一个可以像您期望的那样工作的 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;
    }
}

关于c# - 比较两个相同类型的对象在 C# 中返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29232424/

相关文章:

c++ - 比较两个 std::lists 的内容

java - 删除链表偶数个节点并反向打印

c# - 可用页面文件大小/虚拟内存

c# - 用于从关键字中检索相似词的 API?

c - 删除单向链表中所有出现的元素

python - 从Python中的列表列表中提取槽

c# - 选择最大年龄 C#

C# 到 PHP base64 编码/解码

c# - DDD 中的应用层单元测试是什么样的?

c# - 在自定义模拟类中创建返回 IDisposable 的方法