开发者

compare class using reflection

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

   //set get 开发者_StackOverflow
}

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

   //set get
}

the problem is when i using reflection to iterate User class, i cannot identify Employee class. my code is like this

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

please help, thank you

regards, willy


You can do something like this:

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


how about to select only some properties could be compared. let's say i modify user class

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 
}

I only want to compare username, password, and employee, not createdBy and createdDate. Is there any way to do this? I've tried searching by google, but i found nothing so I can only hardcode it, like this

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜