在日常开发中,我们经常使用反射来动态获取关于类的信息,或者是动态给类实例成员赋值;反射提供了封装程序集、模块和类型的对象(Type 类型)。可以使用反射动态创建类型的实例,将类型绑定到现有对象,或从现有对象获取类型并调用其方法或访问其字段和属性。如果代码中使用了属性,可以利用反射对它们进行访问。
using System.Reflection;
class ReflectionDemo
{
static void Main(string[] args)
{
Assembly myAssembly = Assembly.Load("ReflectionDemo");
var types = myAssembly.GetTypes();//获取类型
foreach (Type type in types)//针对每个类型获取详细信息
{
if (type.Name != "MyClass") continue;
Console.WriteLine($"type name:{type.Name}");
Console.WriteLine($"is interface:{type.IsInterface}");
//获取类型的结构信息
var myConstructors = type.GetConstructors();
Console.WriteLine($"constructor count: {myConstructors.Length}");
//获取类型的字段信息
var myFields = type.GetFields();
Console.WriteLine($"field count: {myFields.Length}");
//获取方法信息
var myMethodInfo = type.GetMethods();
Console.WriteLine($"method count: {myMethodInfo.Length}");
//获取属性信息
var myProperties = type.GetProperties();
Console.WriteLine($"property count: {myProperties.Length}");
//获取事件信息
var myEvents = type.GetEvents();
Console.WriteLine($"event count: {myEvents.Length}");
}
var myClass = myAssembly.CreateInstance("MyClass", true, BindingFlags.Default, null, new object[] { "test" }, null, null);
if (myClass != null)
{
var myClassType = myClass.GetType();
var ageProp = myClassType.GetProperty("Age");
ageProp.SetValue(myClass, 100);
Console.WriteLine($"Age is:{((MyClass)myClass).Age }");
}
Console.ReadLine();
}
}
public class MyClass
{
public int Type = 0;
public MyClass()
{
}
public MyClass(string name)
{
Name = name;
}
public delegate void HandleEvent(string eventName);
public event HandleEvent MyEvent;
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public int GetAge()
{
return Age;
}
public string GetFullName()
{
return $"MyClass.{Name}";
}
}