Content comparison before and after Model modification by reflection

Posted by anujgarg on Thu, 02 Apr 2020 12:25:22 +0200

In the development process, we will encounter such a problem. After editing an object, we want to save the modified contents of the object for future review and accountability.

First, we need to create a User class

 1     public class User
 2     {
 3         private string name;
 4         public string Name
 5         {
 6             get { return name; }
 7             set { name = value; }
 8         }
 9         private string age;
10         public string Age
11         {
12             get { return age; }
13             set { age = value; }
14         }
15         private string sex;
16         public string Sex
17         {
18             get { return sex; }
19             set { sex = value; }
20         }
21     }

Then declare and initialize a User object in the Main function

1             User userA = new User()
2             {
3                 Name = "Li Si",
4                 Age = "25",
5                 Sex = "male",
6             };

Because we want to compare the content before and after editing the object, we need to back up this UserA. Let's make a deep copy

1 User userB = DeepCopyByXml<User>(userA);
 1         /// <summary>
 2         /// Deep copy
 3         /// </summary>
 4         /// <typeparam name="T"></typeparam>
 5         /// <param name="obj"></param>
 6         /// <returns></returns>
 7         public static T DeepCopyByXml<T>(T obj) where T : class
 8         {
 9             object retval;
10             using (MemoryStream ms = new MemoryStream())
11             {
12                 XmlSerializer xml = new XmlSerializer(typeof(T));
13                 xml.Serialize(ms, obj);
14                 ms.Seek(0, SeekOrigin.Begin);
15                 retval = xml.Deserialize(ms);
16                 ms.Close();
17             }
18             return (T)retval;
19         }

The next work is to modify the properties of UserA, and then compare with UserB to realize this function by reflection

        /// <summary>
        /// Model Contrast
        /// </summary>
        /// <typeparam Name="T"></typeparam>
        /// <param Name="oldModel"></param>
        /// <param Name="newModel"></param>
        private static void CompareModel<T>(T oldModel, T newModel) where T : class
        {
            string changeStr = string.Empty;
            PropertyInfo[] properties = oldModel.GetType().GetProperties();
            Console.WriteLine("--------User information modification summary--------");
            foreach (System.Reflection.PropertyInfo item in properties)
            {string name = item.Name;
                object oldValue = item.GetValue(oldModel);
                object newValue = item.GetValue(newModel);
                if (!oldValue.Equals(newValue))
                {
                    Console.WriteLine(name + " : from[" + oldValue + "] Change to [" + newValue + "]");
                }
            }
        }

From the operation results, we have obtained the modified content. The beauty is "Name" and "Age". How to display the property Name in Chinese? Next, we will use the features of C ා

Create a new custom attribute class TableAttribute

    /*     
    The parameter validon specifies the language elements whose properties can be placed. It is a combination of the values of the enumerator AttributeTargets. The default is AttributeTargets.All.
    The parameter AllowMultiple (optional) provides a Boolean value for the AllowMultiple property of the attribute. If true, the feature is versatile. The default value is false (single use).
    The parameter Inherited (optional) provides a Boolean value for the Inherited property of the attribute. If true, the attribute can be Inherited by a derived class. The default value is false (not Inherited).
     */
    [AttributeUsage(AttributeTargets.Class |
    AttributeTargets.Field |
    AttributeTargets.Property,
          AllowMultiple = false,
          Inherited = false)]
    public class TableAttribute : System.Attribute
    {
        private string fieldName;
        private string tableName;
        /// <summary>
        /// Table name
        /// </summary>
        public string TableName
        {
            get { return tableName; }
            set { tableName = value; }
        }
        /// <summary>
        /// Field name
        /// </summary>
        public string FieldName
        {
            get { return fieldName; }
            set { fieldName = value; }
        }
    }

Then modify the User class and add the custom attribute TableAttribute

    /// <summary>
    /// User information entity class
    /// </summary>
    [TableAttribute(TableName = "User information")]
    public class User
    {
        private string name;
        [TableAttribute(FieldName = "Full name")]
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
        private string age;
        [TableAttribute(FieldName = "Age")]
        public string Age
        {
            get { return age; }
            set { age = value; }
        }
        private string sex;
        [TableAttribute(FieldName = "Gender")]
        public string Sex
        {
            get { return sex; }
            set { sex = value; }
        }
    }

Finally, modify the CompareModel method

 1         /// <summary>
 2         /// Model Contrast
 3         /// </summary>
 4         /// <typeparam Name="T"></typeparam>
 5         /// <param Name="oldModel"></param>
 6         /// <param Name="newModel"></param>
 7         private static void CompareModel<T>(T oldModel, T newModel) where T : class
 8         {
 9             string changeStr = string.Empty;
10             PropertyInfo[] properties = oldModel.GetType().GetProperties();
11             Console.WriteLine("--------User information modification summary--------");
12             foreach (System.Reflection.PropertyInfo item in properties)
13             {
14                 TableAttribute tableAttribute = item.GetCustomAttribute<TableAttribute>();
15                 string name = item.Name;
16                 if (tableAttribute != null)
17                     name = tableAttribute.FieldName;
18                 object oldValue = item.GetValue(oldModel);
19                 object newValue = item.GetValue(newModel);
20                 if (!oldValue.Equals(newValue))
21                 {
22                     Console.WriteLine(name + " : from[" + oldValue + "] Change to [" + newValue + "]");
23                 }
24             }
25         }

Let's take a look at the results

Download the full demo: https://files.cnblogs.com/files/LikeHeart/ExampleReflection.zip

(end)

Topics: C# Attribute xml