第三十二式:C# 反射 (内视反观)

绝世
秘籍
冲儿,普通人看东西是向外看(使用对象),但高手可以“内视”(Inspect)。
在程序运行的时候,自己检查自己有哪些属性、方法,甚至查看贴在身上的“符咒”(特性),这叫反射 (Reflection)
就像照镜子一样,看清自己的五脏六腑?

1. 获取类型信息 (Type) - 照妖镜

一切反射的起点是 Type 对象。它记录了一个类的所有秘密。


using System.Reflection;

Swordsman linghu = new Swordsman();
Type t = linghu.GetType(); // 拿出照妖镜

Console.WriteLine("类名:" + t.Name);
Console.WriteLine("命名空间:" + t.Namespace);
        

2. 动态调用 - 隔空取物

哪怕你不知道这个类里有什么方法,反射也能帮你找出来并执行它。


// 1. 找到 "Attack" 方法
MethodInfo method = t.GetMethod("Attack");

// 2. 执行它 (Invoke)
method.Invoke(linghu, null); // 相当于 linghu.Attack()
        

3. 读取特性 - 识符

还记得上一章贴的“门派符”吗?反射可以读出它。


object[] attrs = t.GetCustomAttributes(false);
foreach (var attr in attrs)
{
    if (attr is SectAttribute s)
    {
        Console.WriteLine("发现门派符:" + s.Name);
    }
}
        
反射虽然强大,甚至能访问私有(private)成员(只要你有权限),但它非常慢
而且不安全。除非万不得已(比如写通用的框架),否则少用这招!
🪞

动手时刻:查户口

使用 typeof(string) 获取字符串类的 Type 信息。

遍历并打印出它所有的公开方法名 (GetMethods)。

查看参考答案

Type t = typeof(string);
MethodInfo[] methods = t.GetMethods();

foreach (var m in methods)
{
    Console.WriteLine(m.Name);
}
                    

成就解锁:【天眼通】 获得:照妖镜