它允许程序在运行时获取类型的信息,并能动态地创建对象、调用方法、访问字段和属性等
using System;
using System.IO;
using System.Reflection;
using static System.Net.Mime.MediaTypeNames;
namespace ConsoleApp3
{
public class MyClass
{
private int _myField; //一个私有字段
public string MyProperty { get; set; } //一个公共属性
//一个受保护的方法
protected void ProtectedMethod()
{
Console.WriteLine("Called a protected method");
}
//一个公开的构造函数
public MyClass()
{
_myField = 10;
}
//一个公开的方法
public void PublicMethod()
{
Console.WriteLine("Called a public method");
}
//一个私有的方法
private void PrivateMethod()
{
Console.WriteLine("Called a private method");
}
//一个公开的事件
public event EventHandler MyEvent;
//触发事件的示例
public virtual void OnMyEvent()
{
MyEvent.Invoke(this, EventArgs.Empty);
}
}
class Program
{
static void Main(string[] args)
{
MyClass myCladdInstance = new MyClass();//创建MyClass的实例
Type myClassType = typeof(MyClass); //创建MyClass的Type对象
//获取并调用PublicMethod
MethodInfo publicMethod = myClassType.GetMethod("PublicMethod");
publicMethod.Invoke(myCladdInstance, null);
//获取MyProperty属性并设置值
PropertyInfo myProperty = myClassType.GetProperty("MyProperty");
myProperty.SetValue(myCladdInstance,"123");
//获取_myField私有字段并设置值
FieldInfo myField = myClassType.GetField("_myField");
myField.SetValue(myCladdInstance, 20);
MethodInfo protectedMethod = myClassType.GetMethod("ProtectedMethod",BindingFlags.NonPublic);
protectedMethod.Invoke(myCladdInstance,null);
//触发事件
myCladdInstance.OnMyEvent();
Console.ReadKey();
}
}
}