2011-01-25 98 views
1
public class User 
{ 
    private string _username; 
    private string _password; 
    private Employee _employee; 

    //set get 
} 

public class Employee 
{ 
    private int _id; 
    private string _firstname; 
    private string _lastname; 

    //set get 
} 

問題是當我使用反射來迭代用戶類時,我無法識別Employee類。我的代碼是這樣的使用反射比較類

public string Compare<T>(T newVal, T oldVal) 
{ 
    StringBuilder retVal = new StringBuilder(); 

    Type objectsType = typeof(T); 

    foreach (PropertyInfo propertyInfo in objectsType.GetProperties(
        BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance)) 
    { 
     //if (?) --> how to identify the propertyInfo here as class so that i can iterate using recursive 
     //{ 
     // Compare(propertyInfo.GetValue(oldVal, null), propertyInfo.GetValue(newVal, null)); 
     //} 

     if (propertyInfo.CanRead) 
     { 
     object newValue = propertyInfo.GetValue(newVal, null); 
     object oldValue = propertyInfo.GetValue(oldVal, null); 

     if (propertyInfo.PropertyType.Namespace.StartsWith("System") && !propertyInfo.PropertyType.IsGenericType) 
     { 
      if (!Object.Equals(newValue, oldValue)) 
      { 
       retVal.Append(propertyInfo.Name + " = " + newValue.ToString() + ";"); 
      } 
     } 
     } 
    } 

    return retVal.ToString(); 
} 

請大家幫忙, 謝謝

問候, 威利

+1

似乎有一些非常錯誤的做法。爲什麼不實施`IComparable`? – leppie 2011-01-25 05:03:50

回答

3

你可以做這樣的事情:

if(!propertyInfo.PropertyType.IsValueType && propertyInfo.PropertyType != typeof(string)) 
{ 
    //you're dealing with a class 
} 
+0

它的工作,太棒了!謝謝 – willy 2011-01-25 08:14:24

0

怎麼樣,只選擇一些屬性可以進行比較。假設我修改用戶級別

public class BaseEntity 
{ 
    private string _createdBy; 
    private DateTime _createdDate; 
    private string _updatedBy; 
    private DateTime _updatedDate; 
} 

public class User : BaseEntity 
{ 
    private string _username; 
    private string _password; 
    private Employee _employee; 

    //set get 
} 

我只想比較用戶名,密碼和員工,而不是createdBy和createdDate。有沒有辦法做到這一點?我試着通過谷歌搜索,但我沒有發現任何 所以我只能硬編碼,這樣

if (!propertyInfo.Name.Equals("CreatedDate") || 
!propertyInfo.Name.Equals("CreatedBy")) 
{ 
} 
+0

你應該爲此開始一個新的問題。但是您可以檢查`DeclaringType`屬性以確定成員是否被繼承。 – 2011-01-26 04:34:45