Home  >  Article  >  Backend Development  >  How to set property value via reflection in C#?

How to set property value via reflection in C#?

WBOY
WBOYforward
2023-08-27 15:49:02602browse

How to set property value via reflection in C#?

system. The reflection namespace contains classes that allow you to obtain information about your application and dynamically add types, values, and objects to your application.

Reflection objects are used to obtain type information at runtime. Classes that allow access to a running program's metadata are located in the System.reflection namespace.

Reflection allows viewing property information at runtime.

Reflection allows inspection of various types in an assembly and instantiation of these types.

Reflection allows late binding to methods and properties.

Reflection allows you to create new types at runtime and then use these types to perform some tasks.

Example

GetProperty(String)

Search for a public property with the specified name.

GetType(String, Boolean)

Gets the Type object with the specified name in the assembly instance, optionally throwing an exception if the type is not found.

SetValue(Object, Object)

Set the property value of the specified object.

class Program{
   static void Main(string[] args){
      User user = new User();
      Type type = user.GetType();
      PropertyInfo prop = type.GetProperty("Name");
      prop.SetValue(user, "Bangalore", null);
      System.Console.WriteLine(user.Name);
      Console.ReadLine();
   }
}
class User{
   public int Id { get; set; }
   public string Name { get; set; }
}

Output

Bangalore

The above is the detailed content of How to set property value via reflection in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete