2011-01-25 7 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クラスを識別できません。どのように一部だけを選択することを約リフレクションを使用してクラスを比較する

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

のようなアプローチには非常に間違って何かがあるようですので、私は、それをハードコーディングすることができ、何も が見つかりませんでした。なぜ単にIComparableを実装しないのですか? – leppie

答えて

3

ウィリー はあなたに

に関して、 に感謝し、助けてください。このよう

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

です特性を比較することができた。私がユーザークラスを変更するとします。

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

それは素晴らしい仕事です!ありがとうございます – willy

0

:私のコードは、あなたがこのような何かを行うことができ

+0

あなたのために新しい質問を開始する必要があります。しかし、 'DeclaringType'プロパティをチェックして、メンバーが継承されているかどうかを調べることができます。 –

+0

ok ben、私は新しい質問を開始します。あなたの注意のおかげで – willy

関連する問題