SoFunction
Updated on 2025-03-06

Summary of the use of property PropertyInfo in C#

In C#, PropertyInfo is a class for getting and setting properties. PropertyInfo can be used in the following ways:

1. Get the Type of the attribute:You can use PropertyInfo's PropertyType property to get the type of the property. For example, if there is a property named "Name", you can use the following code to get the type of the property:

PropertyInfo propertyInfo = typeof(ExampleClass).GetProperty("Name");
Type propertyType = ;

2. Get the value of the attribute:You can use PropertyInfo's GetValue method to get the value of the property. An object instance needs to be provided as a parameter to indicate the value of the property obtained from the object. For example:

ExampleClass example = new ExampleClass();
 = "John";
PropertyInfo propertyInfo = typeof(ExampleClass).GetProperty("Name");
object propertyValue = (example);

3. Set the value of the attribute:You can use PropertyInfo's SetValue method to set the value of the property. An object instance and the value to be set need to be provided as parameters. For example:

ExampleClass example = new ExampleClass();
PropertyInfo propertyInfo = typeof(ExampleClass).GetProperty("Name");
(example, "John");

These are some basic usages of PropertyInfo. Other methods and properties can also be used to perform more advanced operations, such as obtaining and setting access modifiers for attributes, properties of attributes, etc.

General properties

Take a look at the completion composition of the general attributes:

1. Private fields are generally set to private, and the attributes are assigned to ensure security:

private string _age;

The accessor is responsible for reading data, which can perform its own logical judgment and data verification, ending with return or throw:

Automatic properties

The above briefly talks about general properties. When no other logic is needed in the property accessor, automatic properties can be used.

public int Id { get; set; }

A brief comparison of the difference between regular attributes and automatic attributes:

1. Automatically implemented properties must declare both get and set accessors. When creating readonly automatic implementation properties, the set accessor needs to be set to private .

2. Features can be used on the properties that are automatically implemented and cannot be used in the support fallback fields. If a property is used on the fallback field of the property, only the general properties should be created.
3. Automatically implement attribute get, and set cannot contain special logical processing. Similar to fields, but different from fields. Unlike fields, attributes are not classified as variables, and attributes cannot be passed as ref parameters or out parameters.

Use of PropertyInfo

Define Person class:

public class Person {
       public Person(int id,string name,string address)
       {
            = id;
            = name;
            = address;
       }
       public int Id { get; set; }
       public string Name { get; set; }
       public string Address { get; set; }
   }

Define User class

public class User {
       public int Id { get; set; }
       public string Name { get; set; }
       public string Group { get; set; }
}

Conversion method:

public static User ConvertObject(User user,Person person)
       {
           PropertyInfo[] userPro = ().GetProperties();
           PropertyInfo[] personPro = ().GetProperties();
           if (>0&&>0)
           {
               for (int i = 0; i < ; i++)
               {
                   for (int j = 0; j < ; j++)
                   {<br>//Judge whether the attribute of the User is in Person                       if (userPro[i].Name == personPro[j].Name && userPro[i].PropertyType == personPro[j].PropertyType)
                       {
                           Object value=personPro[j].GetValue(person, null);
                        //Assign the value of the attribute in Person to User<br>  userPro[i].SetValue(user,value, null);                       }
                   }
               }
           }
           return user;
}

Method calls:

static void Main(string[] args)
      {
          Person person = new Person(1,"FlyElephant","Beijing");
          User user = new User();
           = 20;
          user = ConvertObject(user, person);
          ("Id:" +  + "Name:" +  + "Role:" + );
          ();
      }

2. I used SqlHelper back when I was working on Winform. Now many companies use this. At that time, many things felt like repetitive operations. I once thought programming was just copy and paste. The following code should be very common:

List&lt;Person&gt; list = new List&lt;Person&gt;();
SqlDataReader sdr = new SqlDataReader();
while (())
{
    Person person = new Person();
     = (0);
    //....The following is similar    (person);
}

When I started writing, I felt that it was exercise, but I felt bored after writing too much. In fact, I could completely change the way to implement the above code:

public static List&lt;T&gt; ConvertData&lt;T&gt;(SqlDataReader sdr)
     {
         List&lt;T&gt; list = new List&lt;T&gt;();
         Type type = typeof(T);
         PropertyInfo[] properties = ();
         while (())
         {
             T model = &lt;T&gt;();
             for (int i = 0; i &lt; ; i++)
             {
                 for (int j = 0; j &lt; ; j++)
                 {
                     //Judge whether the name of the attribute and the name of the field are the same                     if (properties[i].Name == (j))
                     {
                         Object value =sdr[j];
                         // Assign the value of the field to the attribute in User                         properties[i].SetValue(model, value, null);
                     }
                 }
             }
             (model);
         }
         return list;
     }
List<User> list = new List<User>();
SqlDataReader sdr = ();
list = ConvertData<User>(sdr);

This is the end of this article about how to use PropertyInfo in C#. For more related content on C# PropertyInfo, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!