使用反射比较类

时间:2011-01-25 04:55:44

标签: c# generics reflection

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
}

问题是当我使用反射来迭代User类时,我无法识别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();
}

请帮忙, 谢谢

的问候, 威利

2 个答案:

答案 0 :(得分:3)

您可以这样做:

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

答案 1 :(得分: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"))
{
}