C#利用反射获取对象属性值和对象属性的修改情况

Table of Contents

1 利用反射获取对象属性值

public static string GetObjectPropertyValue<T>(T t, string propertyname)
{
     Type type = typeof(T);

      PropertyInfo property = type.GetProperty(propertyname);

      if (property == null) return string.Empty;

      object o = property.GetValue(t, null);

      if (o == null) return string.Empty;

      return o.ToString();
}

2 利用对象属性的修改情况

 public static string GetObjectUpdateInfo<T>(T old, T current)
 {
      string info = string.Empty;

      Type type = typeof(T);

      PropertyInfo[] propertys = type.GetProperties();

      foreach (PropertyInfo property in propertys)
      {
          if (property.PropertyType.IsValueType || 
                property.PropertyType.Name == "String")
          {
              if (property.PropertyType.FullName.Contains("Guid")) continue;

              object o1 = property.GetValue(old, null);
              object o2 = property.GetValue(current, null);
              string str1 = o1 == null ? string.Empty : o1.ToString();
              string str2 = o2 == null ? string.Empty : o2.ToString();

              if (str1 != str2) info += property.Name + " from " 
                  + str1 + " to " + str2 + "\r\n    ";
            }
        }

        return info;
}