本文主要是对反射进行详细介绍,具体可以参照微软官方文档
首先我们来定义一个类型
public class Calculator
{private int _number1 = 10;private int _number2 = 20;public int Number1 { get => _number1; set => _number1 = value; }public int Number2 { get => _number2; set => _number2 = value; }public delegate void DataAddedHandler(object sender, EventArgs e);public event DataAddedHandler DataAdded;public void Add(){DataAdded?.Invoke(this, EventArgs.Empty);Console.WriteLine(_number1 + _number2);}public void Divide(int number1, int number2){Console.WriteLine(number1 / number2);}public int Subtract(){return _number1 - _number2;}public int Multiply(){return _number1 * _number2;}public int Multiply(int number1, int number2){return number1 * number2;}
}
通过对象的类型实例化对象
Calculator calculator = Activator.CreateInstance<Calculator>();
获取一个对象的类型
Type type = calculator.GetType();
获取对象里面所有属性信息
PropertyInfo[] propertyInfos = type.GetProperties();
获取对象里面指定的属性
string propertyName = "Number1";
PropertyInfo propertyInfo = type.GetProperty(propertyName);
获取指定属性的值
int number1 = (int)propertyInfo.GetValue(calculator);
设置指定属性的值
propertyInfo.SetValue(calculator, 11);
获取对象的所有方法
MethodInfo[] methodInfos = type.GetMethods();
获取对象里面指定的方法
string methodName = "Add";
MethodInfo methodInfo = type.GetMethod(methodName);
执行不带参数方法
methodInfo?.Invoke(calculator, null);
执行带参数方法
methodName = "Divide";
methodInfo = type.GetMethod(methodName);
methodInfo?.Invoke(calculator, new object[] { 1, 2 });
获取方法的返回值
methodName = "Subtract";
methodInfo = type.GetMethod(methodName);
var subtract = (int)methodInfo?.Invoke(calculator, null);
Console.WriteLine(subtract);
当类里面出现多个相同名称的方法,则需要指定传入参数的类型
methodName = "Multiply";
methodInfo = type.GetMethod(methodName, new Type[]{});
methodInfo?.Invoke(calculator, null);methodName = "Multiply";
methodInfo = type.GetMethod(methodName, new Type[] { typeof(int), typeof(int)});
methodInfo?.Invoke(calculator, new object[] { 1, 2 });
通过反射机制挂载和取消挂载事件
// 需要挂载事件对象里面的方法methodName = "OnDataAdded";MethodInfo method = GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance);// 需要触发事件的名称string eventName = "DataAdded";EventInfo eventInfo = type.GetEvent(eventName);Type eventHandlerType = eventInfo.EventHandlerType;// 挂载事件的实例object target = this; Delegate handler = Delegate.CreateDelegate(eventHandlerType, target, method);// 挂载事件eventInfo.AddEventHandler(calculator, handler);calculator.Add();// 取消挂载事件eventInfo.RemoveEventHandler(calculator, handler);
获取属性的特性
Attribute attribute = propertyInfo.GetCustomAttribute(typeof(DescriptionAttribute));
// 获取特性里面的属性
if (attribute is DescriptionAttribute descriptionAttribute)
{Console.WriteLine(descriptionAttribute.Description);
}