繁体   English   中英

使用反射比较类

[英]compare class using 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();
}

请帮助,谢谢

问候,威利

您可以执行以下操作:

if(!propertyInfo.PropertyType.IsValueType && propertyInfo.PropertyType != typeof(string))
{
   //you're dealing with a 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 
}

我只想比较用户名,密码和员工,而不要比较createdBy和createdDate。 有什么办法吗? 我曾尝试通过Google搜索,但没有找到任何内容,因此只能像这样硬编码

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM