环通的对象属性在C# [英] Loop Through An Objects Properties In C#

查看:103
本文介绍了环通的对象属性在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个同类型的对象,我想通过他们每个人的公共属性环路,并提醒哪些属性不匹配的用户。

I have two objects of the same type, I want to loop through the public properties on each of them and alert the users what properties dont match.

是否有可能做到这一点不知道是什么属性的对象包含了?

Is it possible to do this without knowing what properties the object contains?

感谢

推荐答案

是的,有反思 - 假设每个属性类型实现等于适当。另一种方法是使用 ReflectiveEquals 递归地为所有,但一些已知的类型,但得到棘手。

Yes, with reflection - assuming each property type implements Equals appropriately. An alternative would be to use ReflectiveEquals recursively for all but some known types, but that gets tricky.

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;
}

这篇关于环通的对象属性在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆