Home > Article > Backend Development > 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.
Search for a public property with the specified name.
Gets the Type object with the specified name in the assembly instance, optionally throwing an exception if the type is not found.
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; } }
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!