Skip to main content
 首页 » 编程设计

c#之在 C# 中实现通用对象比较

2024年02月13日12jirigala

我正在实现通用对象比较方法来比较我项目中的类实例。在每个类中,我都有一些值类型变量和它的关联类的一些绑定(bind)列表。对于值类型变量,我可以使用 ==运算符(operator)或 equal运算符来比较它,但是对于绑定(bind)列表,我不知道如何将它转换为 bindinglist<type of associate class>遍历它并执行递归。

public bool IsEqual<T>(T obj1, T obj2) 
{ 
    PropertyInfo[] prop1 = obj1.GetType().GetProperties(); 
    PropertyInfo[] prop2 = obj2.GetType().GetProperties();  
 
    for(int i = 0; i < prop1.Count; i++) 
    { 
        if(prop1[i].IsValueType && prop2[i].IsValueType) 
        { 
            if(prop1.GetValue(i) != prop2.GetValue(i)) 
                return false 
        } 
        else 
        { 
            //This is bindinglist of associate class 
            //I need to cast it to iterate in perform recursion here             
        } 
    } 
 
    return true 
} 

那么当属性是一个绑定(bind)列表时,我该如何实现递归呢?

P/S:原谅我的英文不好

更新:

经过深思熟虑,我实现了IEqualtable正如 Stephen Hewlett 先生所建议的那样。非常感谢您,斯蒂芬·休利特先生。对于那些仍然想使用比较功能的人,我会给你一个我认为可行的方法:

public bool IsEqual(Object obj1, Object obj2) 
{ 
    PropertyInfo[] prop1 = obj1.GetType().GetProperties(); 
    PropertyInfo[] prop2 = obj2.GetType().GetProperties();  
 
    for(int i = 0; i < prop1.Count; i++) 
    { 
        if(prop1[i].IsValueType && prop2[i].IsValueType) 
        { 
            if(prop1[i].GetValue(obj1, null) != prop2[i].GetValue(obj2, null)) 
                return false; 
        } 
        else if (prop1[i].PropertyType.IsGenericType && prop2[i].PropertyType.IsGenericType) //if property is a generic list 
        { 
            //Get actual type of property 
            Type type = prop1[i].PropertyType; 
 
            //Cast property into type 
            var list1 = Convert.ChangeType(prop1[i].GetValue(obj1, null), type); 
            var list2 = Convert.ChangeType(prop1[i].GetValue(obj2, null), type); 
 
            if (list1.count != list2.count) 
                return false; 
 
            for j as integer = 0 to list1.Count - 1 
            { 
                //Recursion here 
                if (!IsEqual(list1(j), list2(j))) 
                { 
                    return false; 
                } 
            } 
        } 
        else //if property is instance of a class 
        { 
            Type type = prop1[i].PropertyType; 
            Object object1 = Convert.ChangeType(prop1[i].GetValue(obj1, null), type); 
            Object object2 = Convert.ChangeType(prop1[i].GetValue(obj2, null), type); 
 
            //Recursion 
            if(!IsEqual(object1, object2)) 
            { 
                 return false; 
            } 
        } 
    } 
 
    return true; 
} 

请您参考如下方法:

我非常非常强烈建议为您的所有类实现 IEquatable - 不管它们有多少 - 因为对不需要它的东西使用反射通常不是一个好主意。 C# 的一个基本优势是通过使用所有内置类型功能获得的类型安全性。通过使用反射,您正在尝试模仿 C# 和 .NET 已经为您所做的事情,您可能会弄错。

你的方法不需要是通用的,因为它使用了反射,所以有问题的对象无论如何都会作为 object 传递给反射方法。添加类型参数没有任何优势。如果没有类型参数,您可以更轻松地根据需要转换绑定(bind)列表。