2009-01-08 60 views
2

我有以下類別:如何使用GetType GetValue來區分兩個對象的屬性值?

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

我怎樣才能提取的屬性值人的角色?

回答

2
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; 
} 
+0

似乎工作,謝謝! – Jeff 2009-01-08 04:09:52

1

如果屬性不是值類型,爲什麼不直接調用DiffObjectProperties並將結果追加到當前列表?據推測,你需要對它們進行迭代,並以點符號的形式預先給定屬性的名稱,以便你可以看到有什麼不同 - 或者知道如果列表是非空的,則當前屬性不同。

0

因爲我不知道如何判斷:

var v1 = p.GetValue(a, null); 

是字符串姓或角色角色。我一直在試圖找出如何判斷v1是否是諸如FirstName或類角色的字符串。因此,我不知道何時遞歸地將對象屬性(Role)傳遞迴DiffObjectsProperties以迭代其屬性值。

相關問題