C#反射获取属性值

        private static void SetModel<T>(T t)
        {
            Type type = typeof (T);
            PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);

            object obj = Activator.CreateInstance(type);
            for (int i = 0; i < props.Length; i++)
            {
                string value = GetPropertyValue<T>(t, props[i].Name);
            }
        }
        private static string GetPropertyValue<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();
        }

 反射获取属性修改情况

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

 

你可能感兴趣的:(C#)