循环遍历C#中的对象属性

我有两个相同类型的对象,我想循环遍历每个对象的公共属性,并提醒用户哪些属性不匹配。

是否可以在不知道对象包含哪些属性的情况下执行此操作?


Smart猫小萌
浏览 1254回答 3
3回答

慕容708150

是的,使用反射 - 假设每种属性类型都Equals适当地实现。另一种方法是ReflectiveEquals递归使用除了一些已知类型之外的所有类型,但这很棘手。public bool ReflectiveEquals(object first, object second){    if (first == null && second == null)    {        return true;    }    if (first == null || second == null)    {        return false;    }    Type firstType = first.GetType();    if (second.GetType() != firstType)    {        return false; // Or throw an exception    }    // This will only use public properties. Is that enough?    foreach (PropertyInfo propertyInfo in firstType.GetProperties())    {        if (propertyInfo.CanRead)        {            object firstValue = propertyInfo.GetValue(first, null);            object secondValue = propertyInfo.GetValue(second, null);            if (!object.Equals(firstValue, secondValue))            {                return false;            }        }    }    return true;}
打开App,查看更多内容
随时随地看视频慕课网APP