C# 反射(Reflection)
系统讲解 C# 反射的运行时元数据层级(程序集、模块、类型、成员)、优缺点权衡、四大核心用途,以及 MemberInfo/Type/MethodInfo 查询自定义特性与动态实例化调用实测。
学完这一章,你能够
- 系统讲解 C# 反射的运行时元数据层级(程序集、模块、类型、成员)、优缺点权衡、四大核心用途,以及 MemberInfo/Type/MethodInfo 查询自定义特性与动态实例化调用实测。
反射概念、元数据层级与工程优缺点
反射(Reflection)指程序在运行期间检查自身或外部程序集的结构元数据,并动态创建实例、绑定成员或调用方法的能力。在 .NET 架构中,程序集(`Assembly`)包含模块(`Module`),模块包含类型(`Type`),类型包含字段、属性、构造函数与方法等成员(`MemberInfo`);`System.Reflection` 命名空间为每一层级都提供了强类型封装对象。
评估是否引入反射时需权衡其利弊:优点在于显著提升框架扩展性与灵活性,能够降低模块耦合、按配置或插件发现机制动态创建并操控未知具体类型而无需提前硬编码;缺点则是反射调用涉及运行时元数据解析与装箱拆箱,性能明显慢于编译期静态直调,同时反射会绕过静态调用链,使源码执行路径变得隐蔽且增加排查维护复杂度。因此反射主要服务于依赖注入容器、ORM、序列化器与插件框架,常规业务逻辑优先使用静态接口与泛型。
反射的四大核心用途
在 .NET 开发中,反射主要承担四类职责:在运行时读取附加在类型与成员上的自定义特性(Attribute)元数据;扫描程序集中的类型清单并借助 `Activator.CreateInstance` 动态实例化;通过 `MethodInfo.Invoke`、`PropertyInfo.SetValue` 实现延迟绑定调用;以及利用 `System.Reflection.Emit` 在运行时动态生成新类型并执行任务。
读取自定义特性元数据与安全反射实测
读取附加在类型上的特性最直接的方式是从 `typeof(TargetClass)` 获取 `MemberInfo`(`Type` 本身继承自 `MemberInfo`),再调用 `GetCustomAttributes(bool inherit)` 返回特性对象数组。以 `HelpAttribute`(含定位参数 `Url` 与命名参数 `Topic`)为例,本站实测从 `typeof(AnnotatedTarget)` 精确检出 `HelpAttribute` 实例并读取其 `Url` 与 `Topic` 属性值。
结合上一章构建的 `DeBugInfo` 特性,可以先调用 `typeof(Rectangle).GetCustomAttributes(typeof(DeBugInfo), false)` 遍历类级特性,再通过 `type.GetMethods(...)` 遍历各方法并调用 `MethodInfo.GetCustomAttributes(typeof(DeBugInfo), true)` 检出方法级特性。工程安全提醒:若目标元素同时附加了其他类型特性,直接强转 `(DeBugInfo)a` 会抛出 `InvalidCastException`,应优先使用重载 `GetCustomAttributes(typeof(DeBugInfo), ...)` 或 `as DeBugInfo` 判空;同时 CLR 不保证多重特性的返回顺序,需要确定性输出时应对结果显式排序。本站实测还额外验证了 `Activator.CreateInstance` 动态构造 `Rectangle(4.5, 7.5)`、`MethodInfo.Invoke` 计算面积 `33.75` 以及 `PropertyInfo.SetValue` 动态修改宽度后重新求得面积 `45`。
运行 csc.exe (.NET Framework 4.x) MemberInfo 特性查询、DeBugInfo 元数据遍历与延迟绑定实测
展开查看收起
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Text;
namespace CSharpReflectionLab
{
[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : Attribute
{
public readonly string Url;
private string topic;
public string Topic
{
get { return topic; }
set { topic = value; }
}
public HelpAttribute(string url)
{
this.Url = url;
}
}
[Help("Information on the class MyClass", Topic = "ReflectionBasics")]
internal class AnnotatedTarget
{
}
[AttributeUsage(
AttributeTargets.Class |
AttributeTargets.Constructor |
AttributeTargets.Field |
AttributeTargets.Method |
AttributeTargets.Property,
AllowMultiple = true)]
public class DeBugInfo : Attribute
{
private readonly int bugNo;
private readonly string developer;
private readonly string lastReview;
private string message;
public DeBugInfo(int bg, string dev, string d)
{
this.bugNo = bg;
this.developer = dev;
this.lastReview = d;
}
public int BugNo { get { return bugNo; } }
public string Developer { get { return developer; } }
public string LastReview { get { return lastReview; } }
public string Message
{
get { return message; }
set { message = value; }
}
}
[DeBugInfo(45, "Zara Ali", "12/8/2012", Message = "Return type mismatch")]
[DeBugInfo(49, "Nuha Ali", "10/10/2012", Message = "Unused variable")]
internal class Rectangle
{
public double Length { get; set; }
public double Width { get; set; }
public Rectangle(double l, double w)
{
Length = l;
Width = w;
}
[DeBugInfo(55, "Zara Ali", "19/10/2012", Message = "Return type mismatch")]
public double GetArea()
{
return Length * Width;
}
[DeBugInfo(56, "Zara Ali", "19/10/2012")]
public string Describe()
{
return string.Format(CultureInfo.InvariantCulture, "{0}x{1}={2}", Length, Width, GetArea());
}
}
internal class Program
{
private static string Esc(string s)
{
if (s == null) return "null";
StringBuilder sb = new StringBuilder("\"");
foreach (char c in s)
{
switch (c)
{
case '\\': sb.Append("\\\\"); break;
case '"': sb.Append("\\\""); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
default:
if (c < 32) sb.AppendFormat("\\u{0:x4}", (int)c);
else sb.Append(c);
break;
}
}
sb.Append("\"");
return sb.ToString();
}
private static string CaseJson(string name, string summary, string expected, string actual)
{
bool passed = string.Equals(expected, actual, StringComparison.Ordinal);
return string.Format(
"{{\"name\":{0},\"summary\":{1},\"expected\":{2},\"actual\":{3},\"passed\":{4}}}",
Esc(name), Esc(summary), Esc(expected), Esc(actual), passed ? "true" : "false"
);
}
public static void Main(string[] args)
{
Console.OutputEncoding = Encoding.UTF8;
List<string> cases = new List<string>();
// Case 1: MemberInfo + HelpAttribute reflection
MemberInfo info = typeof(AnnotatedTarget);
object[] helpAttrs = info.GetCustomAttributes(true);
HelpAttribute h = helpAttrs[0] as HelpAttribute;
string actual1 = string.Format("type={0};url={1};topic={2}", h.GetType().Name, h.Url, h.Topic);
cases.Add(CaseJson(
"memberinfo_help_attribute_inspection",
"Inspect HelpAttribute attached to AnnotatedTarget via MemberInfo.GetCustomAttributes(true)",
"type=HelpAttribute;url=Information on the class MyClass;topic=ReflectionBasics",
actual1
));
// Case 2: Inspect Rectangle class & method DeBugInfo metadata
Type rectType = typeof(Rectangle);
List<string> classRecords = new List<string>();
foreach (object attr in rectType.GetCustomAttributes(typeof(DeBugInfo), false))
{
DeBugInfo dbi = attr as DeBugInfo;
if (dbi != null)
{
classRecords.Add(string.Format("{0}:{1}:{2}", dbi.BugNo, dbi.Developer, dbi.Message ?? ""));
}
}
classRecords.Sort(StringComparer.Ordinal);
List<string> methodRecords = new List<string>();
foreach (MethodInfo m in rectType.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
foreach (object attr in m.GetCustomAttributes(typeof(DeBugInfo), true))
{
DeBugInfo dbi = attr as DeBugInfo;
if (dbi != null)
{
methodRecords.Add(string.Format("{0}#{1}:{2}", m.Name, dbi.BugNo, dbi.Message ?? ""));
}
}
}
methodRecords.Sort(StringComparer.Ordinal);
string actual2 = string.Join("|", classRecords.ToArray()) + "||" + string.Join("|", methodRecords.ToArray());
cases.Add(CaseJson(
"debuginfo_class_and_method_metadata",
"Inspect class-level and method-level DeBugInfo custom attributes on Rectangle via Type and MethodInfo",
"45:Zara Ali:Return type mismatch|49:Nuha Ali:Unused variable||Describe#56:|GetArea#55:Return type mismatch",
actual2
));
// Case 3: Dynamic instantiation, late-bound method invocation & property access
object dynRect = Activator.CreateInstance(rectType, new object[] { 4.5, 7.5 });
MethodInfo areaMethod = rectType.GetMethod("GetArea");
double area1 = (double)areaMethod.Invoke(dynRect, null);
PropertyInfo widthProp = rectType.GetProperty("Width");
widthProp.SetValue(dynRect, 10.0, null);
double area2 = (double)areaMethod.Invoke(dynRect, null);
string actual3 = string.Format(CultureInfo.InvariantCulture, "area1={0};area2={1}", area1, area2);
cases.Add(CaseJson(
"dynamic_instantiation_and_late_binding",
"Verify Activator.CreateInstance, MethodInfo.Invoke, and PropertyInfo.SetValue late binding",
"area1=33.75;area2=45",
actual3
));
// Case 4: Assembly -> Module -> Type -> MemberInfo hierarchy
Assembly asm = rectType.Assembly;
Module mod = rectType.Module;
bool sameType = mod.GetType("CSharpReflectionLab.Rectangle") == rectType;
bool safeFilter = rectType.GetCustomAttributes(typeof(HelpAttribute), false).Length == 0;
string actual4 = string.Format("hasAsm={0};sameType={1};safeFilter={2}", asm != null, sameType, safeFilter);
cases.Add(CaseJson(
"assembly_module_type_hierarchy",
"Verify Assembly -> Module -> Type lookup and typed GetCustomAttributes filtering safety",
"hasAsm=True;sameType=True;safeFilter=True",
actual4
));
Console.WriteLine(string.Format(
"{{\"version\":\"csc4/{0}\",\"cases\":[{1}]}}",
Environment.Version.ToString(),
string.Join(",", cases.ToArray())
));
}
}
}
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
一个类型或方法可能同时标注了编译器生成或框架提供的其他特性;直接强制转换会在遇到非 `DeBugInfo` 实例时抛出 `InvalidCastException`,传入目标特性类型过滤或使用 `as` 安全判空可避免运行期异常。