Reflection in C# refers to a mechanism that allows a program to dynamically obtain and manipulate type information at runtime. Through reflection, we can obtain the type at runtime, access the members of the type (properties, methods, fields, etc.), create instances and call methods, and even dynamically modify the members of the type.
Reflection is very useful in many scenarios, especially when writing general code or frameworks. It allows us to dynamically load and use types based on information without knowing the specific type.
Reflection in C# is mainly supported by some classes and interfaces under the System.Reflection
namespace. Among them, the Assembly
class is used to load and access assembly information, the Type
class is used to obtain and operate type information, and the MethodInfo
class is used to obtain and operate method information. , PropertyInfo
class is used to obtain and operate property information, etc.
The following uses a specific code example to demonstrate how to use reflection.
using System; using System.Reflection; class MyClass { public int MyProperty { get; set; } public void MyMethod() { Console.WriteLine("Hello, reflection!"); } } class Program { static void Main(string[] args) { // 加载程序集 Assembly assembly = Assembly.GetExecutingAssembly(); // 获取类型 Type myClassType = assembly.GetType("MyNamespace.MyClass"); // 创建实例 object myClassInstance = Activator.CreateInstance(myClassType); // 获取属性 PropertyInfo myProperty = myClassType.GetProperty("MyProperty"); // 设置属性值 myProperty.SetValue(myClassInstance, 42); // 获取方法 MethodInfo myMethod = myClassType.GetMethod("MyMethod"); // 调用方法 myMethod.Invoke(myClassInstance, null); } }
The above code first obtains the information of the current assembly through the Assembly.GetExecutingAssembly()
method, and then uses the GetType
method to obtain the MyClass
Type
Object. Next, an instance of MyClass
is created through the Activator.CreateInstance
method.
Through reflection, we obtained the information of MyProperty
and MyMethod
, and used the SetValue
method to set the value of the property, using The Invoke
method calls the method.
Through this simple example, we can see the power of reflection, which allows us to dynamically load, access and modify members of a type at runtime, achieving a more flexible and versatile code design. However, reflection may bring performance overhead, so it needs to be used with caution in scenarios with high performance requirements.
The above is the detailed content of Introduction to reflection mechanism in C#. For more information, please follow other related articles on the PHP Chinese website!