如何比较用户创建的类的所有元素

时间:2015-02-18 19:36:52

标签: c#

我有一个定义为:

的类
public class TableInfo
{
    public int item_id { get; set:}
    public string item_name { get; set;}
    // plus several more
}

我创建了这个类的两个实例,它们填充了不同的信息,并希望对它们进行比较。我一直在努力做到这一点:

if(table1[index1].item_id == table2[index2].item_id)
    //report passed
else
    //report failed

然后再对类中的每个元素执行此操作。

if(table1[index1].item_name == table2[index2].item_name)

等等。

有没有更好的方法来处理这个问题,这样我就不必对每个元素进行独特的比较。在我看来,foreach可以做到,但我不知道如何获取属性列表并迭代它们。

4 个答案:

答案 0 :(得分:4)

您可以实现类的相等比较,然后使用Equals进行比较:

public class TableInfo
{
    public int item_id { get; set;}
    public string item_name { get; set;}

    public override bool Equals(object obj)
    {
        if(obj == null)
            return false;
        if (ReferenceEquals(obj, this))
            return true;
        if (obj.GetType() != this.GetType())
            return false;
        var rhs = obj as TableInfo;
        return item_id == rhs.item_id && item_name == rhs.item_name;
    }

    public override int GetHashCode()
    {
        return item_id.GetHashCode() ^ item_name.GetHashCode();
    }

    // Additionally you can overload == and != operators:
    public static bool operator ==(TableInfo x, TableInfo y)
    {
        return object.Equals(x, y);
    }

    public static bool operator !=(TableInfo x, TableInfo y)
    {
        return !object.Equals(x, y);
    }
}

然后而不是使用

if(table1[index1].item_id == table2[index2].item_id)

你可以使用

if(table1[index1].Equals(table2[index2]))

如果运算符过载,您可以使用

if(table1[index1] == table2[index2])

答案 1 :(得分:0)

你可以用Reflection解决它 只是展示了另一种方法,但实现相等比较会更清晰

  

此代码段仅比较公共属性

    static bool IsFullyEqual(object obj1, object obj2)
    {
        if (obj1.GetType() != obj2.GetType()) return false;

        bool result = true;
        foreach (var property in obj1.GetType().GetProperties())
        {
            object obj1Value = property.GetMethod.Invoke(obj1, null);
            object obj2Value = property.GetMethod.Invoke(obj2, null);
            if( obj1Value.GetHashCode()!= obj2Value.GetHashCode())
            {
                result = false;
                break;
            }
        }
        return result;
    }

答案 2 :(得分:0)

您可能想要做的是在TableInfo类上实现IComparable。以下是一些有关实施IComparable的信息的链接。

https://msdn.microsoft.com/en-us/library/system.icomparable(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/system.icomparable.compareto(v=vs.110).aspx IComparable and Equals()

答案 3 :(得分:0)

如果您只是比较两个项目,则可以使用Type.GetType()。GetProperties()方法,该方法返回对象中所有公共属性的数组。从这里,您可以使用foreach循环遍历类型上的每个属性并比较您的字段。

https://msdn.microsoft.com/en-us/library/aky14axb%28v=vs.110%29.aspx