.dll
或 .exe
文件。文件夹路径 | 是否编译 | 生成的程序集名称 |
---|---|---|
Assets/Scripts/ | ✅ | Assembly-CSharp.dll (主逻辑) |
Assets/Plugins/ | ✅ | Assembly-CSharp-firstpass.dll |
Assets/Editor/ | ✅ | Assembly-CSharp-Editor.dll |
使用 .asmdef 自定义目录 | ✅ | 自定义模块程序集(如 Game.UI.dll ) |
.asmdef
可手动拆分模块,提升编译效率与解耦性;Library/ScriptAssemblies/
目录。.dll
中;元数据项 | 示例 |
---|---|
类型名 | public class Player |
字段信息 | public int HP |
方法签名 | public void Move(float spd) |
特性(Attribute) | [Serializable] |
参数/返回类型等 | 用于反射调用或自动匹配 |
用途 | 示例 |
---|---|
动态创建对象 | Activator.CreateInstance(type) |
获取字段/方法信息 | type.GetField("Name") |
调用方法 | method.Invoke(obj, null) |
获取/设置字段值 | field.GetValue(obj) / SetValue(...) |
获取自定义特性 | GetCustomAttribute<T>() |
Assembly.Load("xxx.dll") ↓ GetType("命名空间.类名") ↓ 构建 Type/FieldInfo/MethodInfo ↓ 动态创建对象 / 获取字段 / 调用方法
场景 | 使用反射 | 使用元数据 | 说明 |
---|---|---|---|
热更新框架(ILRuntime) | ✅ | ✅ | 动态加载、调用模块 |
导表工具(JSON映射) | ✅ | ✅ | 自动字段绑定无需硬编码 |
插件系统/自动注册 | ✅ | ✅ | 自动注册模块,减少手工操作 |
编辑器工具生成 | ✅ | ✅ | 自动化生成 Inspector 字段列表 |
特性驱动的行为扩展 | ✅ | ✅ | 利用 Attribute 实现数据驱动 |
关键词 | 含义 |
---|---|
Assembly | 程序集,最终产物 .dll /.exe |
Metadata | 记录程序结构的描述信息,写入程序集内部 |
Reflection | 运行时动态获取类型信息、字段、方法等操作 |
.csproj | 告诉编译器哪些文件组成项目,如何编译生成程序集 |
.asmdef | Unity 中手动拆分程序集的配置文件 |
IL | 中间语言代码(Intermediate Language) |
csharpType type = typeof(MyClass);
Type type2 = obj.GetType();
csharpobject obj = Activator.CreateInstance(type);
带参数构造函数:
csharpobject obj = Activator.CreateInstance(type, new object[] { "Tom", 18 });
csharpFieldInfo field = type.GetField("name");
object value = field.GetValue(obj);
field.SetValue(obj, "NewName");
访问私有字段:
csharpvar field = type.GetField("hp", BindingFlags.NonPublic | BindingFlags.Instance);
csharpvar prop = type.GetProperty("Score");
var val = prop.GetValue(obj);
prop.SetValue(obj, 99);
csharpvar method = type.GetMethod("Attack");
method.Invoke(obj, new object[] { 10 });
csharpvar ctor = type.GetConstructor(Type.EmptyTypes);
var obj = ctor.Invoke(null);
csharpforeach (var f in type.GetFields()) Console.WriteLine(f.Name);
csharpvar attr = field.GetCustomAttribute<ObsoleteAttribute>();
if (attr != null) Console.WriteLine("该字段已过时");
csharpvar asm = Assembly.LoadFrom("MyLib.dll");
var type = asm.GetType("MyLib.Foo");
var obj = Activator.CreateInstance(type);
功能 | 常用 API |
---|---|
获取类型 | typeof(T) / obj.GetType() |
创建实例 | Activator.CreateInstance(type) |
获取字段/属性/方法 | GetField() / GetProperty() / GetMethod() |
批量获取 | GetFields() / GetMethods() |
访问字段/属性值 | GetValue() / SetValue() |
调用方法 | Invoke() |
获取构造函数 | GetConstructor() / ConstructorInfo.Invoke() |
加载程序集 | Assembly.Load() / LoadFrom() |
获取特性(Attribute) | GetCustomAttribute<T>() |
什么是反射?
反射是 C# 中一种运行时机制,它允许程序在不知道类型定义的情况下,动态获取类型信息、创建对象、访问字段、调用方法
反射的原理是?
C# 编译后生成的程序集(DLL 或 EXE)中包含了类型的元数据,这些元数据记录了类的结构(包括字段、属性、方法、特性等)。 运行时通过 .NET 提供的 System.Reflection 命名空间读取这些元数据,并通过 Type、FieldInfo、MethodInfo 等对象实现动态操作。
本文作者:xuxuxuJS
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!