为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Smart猫小萌 2019-09-20 15:29:24
我有两个相同类型的对象,我想循环遍历每个对象的公共属性,并提醒用户哪些属性不匹配。是否可以在不知道对象包含哪些属性的情况下执行此操作?
查看完整描述

3 回答

?
慕容708150

TA贡献1831条经验 获得超4个赞

是的,使用反射 - 假设每种属性类型都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;

}


查看完整回答
反对 回复 2019-09-20
  • 3 回答
  • 0 关注
  • 1250 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信