一切反射的起点是 Type 对象。它记录了一个类的所有秘密。
using System.Reflection;
Swordsman linghu = new Swordsman();
Type t = linghu.GetType(); // 拿出照妖镜
Console.WriteLine("类名:" + t.Name);
Console.WriteLine("命名空间:" + t.Namespace);
哪怕你不知道这个类里有什么方法,反射也能帮你找出来并执行它。
// 1. 找到 "Attack" 方法
MethodInfo method = t.GetMethod("Attack");
// 2. 执行它 (Invoke)
method.Invoke(linghu, null); // 相当于 linghu.Attack()
还记得上一章贴的“门派符”吗?反射可以读出它。
object[] attrs = t.GetCustomAttributes(false);
foreach (var attr in attrs)
{
if (attr is SectAttribute s)
{
Console.WriteLine("发现门派符:" + s.Name);
}
}
使用 typeof(string) 获取字符串类的 Type 信息。
遍历并打印出它所有的公开方法名 (GetMethods)。
Type t = typeof(string);
MethodInfo[] methods = t.GetMethods();
foreach (var m in methods)
{
Console.WriteLine(m.Name);
}