我有以下课程:

public class Person
{
    public String FirstName { set; get; }
    public String LastName { set; get; }
    public Role Role { set; get; }
}

public class Role
{
    public String Description { set; get; }
    public Double Salary { set; get; }
    public Boolean HasBonus { set; get; }
}


我希望能够自动提取Person1和Person2之间的属性值差异,如下所示:

public static List<String> DiffObjectsProperties(T a, T b)
{
    List<String> differences = new List<String>();
    foreach (var p in a.GetType().GetProperties())
    {
        var v1 = p.GetValue(a, null);
        var v2 = b.GetType().GetProperty(p.Name).GetValue(b, null);

        /* What happens if property type is a class e.g. Role???
         * How do we extract property values of Role?
         * Need to come up a better way than using .Namespace != "System"
         */
        if (!v1.GetType()
            .Namespace
            .Equals("System", StringComparison.OrdinalIgnoreCase))
            continue;

        //add values to differences List
    }

    return differences;
}


如何提取角色角色的属性值???

最佳答案

public static List<String> DiffObjectsProperties(object a, object b)
{
    Type type = a.GetType();
    List<String> differences = new List<String>();
    foreach (PropertyInfo p in type.GetProperties())
    {
        object aValue = p.GetValue(a, null);
        object bValue = p.GetValue(b, null);

        if (p.PropertyType.IsPrimitive || p.PropertyType == typeof(string))
        {
            if (!aValue.Equals(bValue))
                differences.Add(
                    String.Format("{0}:{1}!={2}",p.Name, aValue, bValue)
                );
        }
        else
            differences.AddRange(DiffObjectsProperties(aValue, bValue));
    }

    return differences;
}

关于c# - 如何使用GetType GetValue区分两个对象的属性值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/423157/

10-11 11:56