C# 反射与互操作

2777 字
14 分钟
C# 反射与互操作

SAST .NET Ignite 讲稿#

反射#

运行时获取类型信息 也是一种用于抽象的方法

使用例#

分支委派

int op = int.Parse(Console.ReadLine()!);
if (op == 0)
{
Console.WriteLine("Do Task 0;");
}
else if (op == 1)
{
Console.WriteLine("Do Task 1;");
}
else if (op == 2)
{
Console.WriteLine("Do Task 2;");
}
else
{
Console.WriteLine("Do other task;");
}

一个很常见的范式
分支体过长->封装多态
懒得手写分支if/switch,根据输入(多数为字符串)调用对应的类型/函数

try
{
var type = Type.GetType(name, throwOnError: true, ignoreCase: true)!;
var instance = Activator.CreateInstance(type);
type.GetProperty("Name")!.SetValue(instance, "hachimi");
type.GetMethod("Speak")!.Invoke(instance, []);
}
catch (TypeLoadException)
{
Console.WriteLine($"Type '{name}' not found.");
return;
}
Warning

这是完全使用反射构建实例并调用函数的例子,实则大可不必并且容易被达斯

Caution

实际应用中切勿直接使用用户输入获取类型信息,会引入安全问题


实际场景例子:ASP.NET,免试题Web方向

namespace SASTCsharpBlogPart.Controllers;
/// <summary>
/// 博客文章 API。写操作需登录。
/// </summary>
[ApiController]
[Route("api/blogitem")]
public class BlogItemController(BlogItemService blogService) : ControllerBase
{
/// <summary>获取全部博客。</summary>
[HttpGet]
public async Task<ActionResult<List<BlogItem>>> GetAll()
{
return Ok(await blogService.GetAllAsync());
}
/// <summary>按 Id 获取博客。</summary>
[HttpGet("{id}")]
public async Task<ActionResult<BlogItem>> GetById(int id)
{
var blogItem = await blogService.GetByIdAsync(id);
return blogItem is null ? NotFound() : Ok(blogItem);
}
}

大量使用反射

  • 首先两个Attribute(ApiControllerAttribute、RouteAttribute),启动时框架扫描类型特性
  • 通过URL路径映射到对应Controller类(虽然这里指明了api/blogitem)
  • 通过参数名id 映射到参数
  • 构造函数传入BlogItemService,由框架自动注入(依赖注入DI)

另一个例子#

truebigsand
/
ConsoleMusicPlayer
Repository details unavailable
—
—
—
Unavailable

完全使用反射的玩具项目
包含两个音乐源(本地、网易云)之后实在写不下去了

代码约束:不使用纯if/switch进行分支委派~~(除了目录,因为实在没招了),~~所有的结构性代码只写一遍(例如在一个class中定义了一个平台就不再在菜单中手写判断该平台的逻辑)

构思项目:将不同的音乐源抽象为一套接口,需要分析不同音乐源的构造方式

  • 本地:参数为路径,不需要其他配置
  • 网易云:参数为歌单ID,需要账号信息(登录方法又包括手机号/密码、邮箱/密码)
ConsoleMusicPlayer
├─ MusicPlatformAccount
│ ├─ IMusicPlatformAccount.cs
│ └─ NeteaseCloudMusicAccount.cs
├─ SongSource
│ ├─ ISongSource.cs
│ ├─ LocalStorage.cs
│ └─ NeteaseCloudMusicShareLink.cs
├─ Config.cs
└─ Program.cs

重量级的玩意在于主程序Program.cs,菜单写在这里

那么要如何从选择音乐源开始到播放想要的音乐呢?(

  1. 获取所有的音乐源(其实这里应该用nameof的但不知道当时为什么没写)
    通过反射获取当前程序集所有类型信息,并从中选出实现了ISongSource接口的类(即所有音乐源)
var songSourceTypes = from type in Assembly.GetExecutingAssembly().GetTypes()
where type.GetInterface("ISongSource") != nullselect type;
  1. 通过对应的参数构造出一个音乐源实例
    这就又有了一个问题:有的音乐源不止一种构造方式,如本地音乐可以选择绝对路径和用户文件夹
    于是需要根据构造函数的信息来让用户选择~~(都用反射了硬编码肯定是不可能硬编码的)~~
var constructors = songSourceType.GetConstructors();
ConstructorInfo constructor;
if (constructors.Length == 1)
{
constructor = constructors.First();
}
else
{
constructor = Prompt.Select("Please select a way to construct the SongSource", constructors, textSelector: (ConstructorInfo x) =>
{
StringBuilder sb = new StringBuilder("Construct with ");
var parameters = x.GetParameters();
for (int i = 0; i < parameters.Length; i++)
{
if (i != 0)
sb.Append(", ");
sb.Append(parameters[i].Name);
sb.Append('(');
sb.Append(parameters[i].ParameterType.Name);
sb.Append(')');
}
return sb.ToString();
});
}

选好之后再根据构造函数的参数让用户一个个输入

var constructorParameters = new List<ParameterInfo>(constructor.GetParameters());
var constructorArgs = new List<object?>();
var requireAccountAttribute = constructor.GetCustomAttribute<RequireMusicPlatformAccountAttribute>();
if (requireAccountAttribute != null)
{
var validAccounts = Config.PersistantStorage.MusicPlatformAccounts
.Where(requireAccountAttribute.AccountType.IsInstanceOfType);
if (validAccounts.Count() > 1)
{
constructorArgs.Add(Prompt.Select("Please select an account to use for this SongSource", validAccounts));
}
else
{
constructorArgs.Add(validAccounts.First());
}
constructorParameters.RemoveAt(0);
}
foreach (var parameter in constructorParameters)
{
var content = (typeof(Prompt).GetMethod("Input", new Type[] { typeof(string), typeof(object), typeof(string), typeof(IList<Func<object, ValidationResult>>) })
?? throw new Exception("Fatal Error: Package Sharprompt Static Method Input Parameter isn't Corresponding!"))
.MakeGenericMethod(new Type[] { parameter.ParameterType })
.Invoke(null, new object?[] { $"Please input {parameter.Name} of this SongSource", null, null, null });
constructorArgs.Add(content);
}

值得一提的是这里对Prompt.Input也采用了反射调用,因为参数的类型可能不同,需要调用对应泛型类型版本的Prompt.Input

(中间收起了一些处理账号的部分,这部分与音乐源的构造过程类似,还有用于持久化配置的Config.cs及在其他类的适配JsonProperty之类的~~,为保护读者的眼睛不再展开~~

var songSourceTypes = from type in Assembly.GetExecutingAssembly().GetTypes()
where type.GetInterface("ISongSource") != nullselect type;
var songSourceType = Prompt.Select("Please select a song source type", songSourceTypes);
var constructors = songSourceType.GetConstructors();
ConstructorInfo constructor;
if (constructors.Length == 1)
{
constructor = constructors.First();
}
else
{
constructor = Prompt.Select("Please select a way to construct the SongSource", constructors, textSelector: (x) =>
{
StringBuilder sb = new StringBuilder("Construct with ");
var parameters = x.GetParameters();
for (int i = 0; i < parameters.Length; i++)
{
if (i != 0)
sb.Append(", ");
sb.Append(parameters[i].Name);
sb.Append('(');
sb.Append(parameters[i].ParameterType.Name);
sb.Append(')');
}
return sb.ToString();
});
}
var constructorParameters = new List<ParameterInfo>(constructor.GetParameters());
var constructorArgs = new List<object?>();
var requireAccountAttribute = constructor.GetCustomAttribute<RequireMusicPlatformAccountAttribute>();
if (requireAccountAttribute != null)
{
var validAccounts = Config.PersistantStorage.MusicPlatformAccounts
.Where(requireAccountAttribute.AccountType.IsInstanceOfType);
if (validAccounts.Count() == 0)
{
ConsoleWriteErrorLine($"This SongSource needs an account of {requireAccountAttribute.AccountType}! Please login and try again.");
continue;
}
IMusicPlatformAccount account;
if (validAccounts.Count() > 1)
{
account = Prompt.Select("Please select an account to use for this SongSource", validAccounts);
}
else
{
account = validAccounts.First();
}
constructorArgs.Add(account);
constructorParameters.RemoveAt(0);
}
foreach (var parameter in constructorParameters)
{
var content = (typeof(Prompt).GetMethod("Input", new Type[] { typeof(string), typeof(object), typeof(string), typeof(IList<Func<object, ValidationResult>>) })
?? throw new Exception("Fatal Error: Package Sharpromt Static Method Input Parameter isn't Corresponding!"))
.MakeGenericMethod(new Type[] { parameter.ParameterType })
.Invoke(null, new object?[] { $"Please input {parameter.Name} of this SongSource", null, null, null });
constructorArgs.Add(content);
//Console.Title = content.ToString();
}
try
{
Config.PersistantStorage.SongSources.Add((ISongSource)songSourceType.GetConstructors().First().Invoke(constructorArgs.ToArray()));
// 不能用Activator,麻了
}
catch (TargetInvocationException ex)
{
ConsoleWriteErrorLine(ex.InnerException.Message);
}
  1. 获取到最终的音乐文件链接之后,使用NAudio就可以轻松播放了,再加上一些控制台界面的适配,一个闹麻的音乐播放器就做好了

特性 Attribute#

[RequireMusicPlatformAccount(typeof(NetEaseCloudMusicAccount))]
public NetEaseCloudMusicShareLink(IMusicPlatformAccount account, string ShareLinkUri)

在定义网易云音乐源时,采用了特性的方式来声明它需要音乐平台账号

enum MenuOperation
{
[EnumText("播放音乐")]
Play,
[EnumText("管理歌曲源")]
ManageSongSource,
[EnumText("管理音乐平台账户")]
ManageMusicPlatformAccount,
[EnumText("退出")]
Quit
}

类似地,菜单界面的文本也是通过特性映射到对应enum项上的,与前面Asp.net的Controller特性类似
这些特性可以在不改变现有代码结构的前提下添加额外信息,可以通过反射获取它们的信息
以上面菜单MenuOption为例:

options.TextSelector = (T enumValue) =>
{
EnumText? enumText = (EnumText?)typeof(T).GetField(Enum.GetName(typeof(T), enumValue))!.GetCustomAttribute(typeof(EnumText));
if (enumText != null)
{
return enumText.Text;
}
return enumValue.ToString();
};

先通过枚举的选项获取枚举字段的类型信息,再获取类型上的特性,从而得到我们定义的特性的实例
我们自定义的EnumText特性有Text这个字段用来存文本,于是可以获取到界面的文本


提到特性就不得不提到面向切面编程(AOP),反射就是它的经典实现方式之一
面向切面编程使得代码专注于业务逻辑实现,日志、参数验证等可复用的中间组件由特性实现

扩展:面向切面编程及其他语言的示例

反射的特性#

  • 灵活性👍👍
  • 可读性❌❌
  • 慢!

有多慢?

[Benchmark]
public void Reflection()
{
var type = Type.GetType("Dog")!;
var instance = Activator.CreateInstance(type);
type.GetProperty("Name")!.SetValue(instance, "hachimi");
type.GetMethod("Speak")!.Invoke(instance, []);
}
[Benchmark]
public void Virtual()
{
Animal animal = new Dog { Name = "hachimi" };
animal.Speak();
}
[Benchmark]
public void Direct()
{
var dog = new Dog { Name = "hachimi" };
dog.Speak();
}

BenchmarkDotNet 结果
BenchmarkDotNet 结果

在现代.NET中,得益于动态PGO和GDV技术,虚函数调用如果在运行时发现目标始终一致,JIT可以将其去虚拟化并内联,因此这里虚函数调用和直接调用体现出来的开销都是几乎为0。而反射不仅会阻止内联,还会带来极大的运行时解析开销。

如何加速#

上面的例子慢在于每次执行都要从零开始获取类型、创建实例、填充属性、获取方法并最终执行,而不仅仅在于MethodInfo.Invoke,实际上是在对比完整反射流水线与静态调用的区别

但MethodInfo.Invoke的开销也可以达到100ns,更进一步优化可以将方法缓存为Delegate,调用Delegate的开销就与直接调用函数相当了

还能更快吗?有的
源生成器(SourceGenerator):编译时添加新的代码从而让运行时的开销真正为0

互操作#

实例#

以刚才的播放器为例,“轻松”播放在哪?只需三行代码就可以放出声音

var waveOut = new WaveOutEvent();
waveOut.Init(reader);
waveOut.Play();

而在Windows平台下NAudio最终调用的是winmm.dll中的waveOutWrite

深入NAudio库,内部有这样一类函数定义

[DllImport("winmm.dll", SetLastError = true)]
public static extern MmResult waveOutOpen(
out IntPtr phwo,
IntPtr uDeviceID,
ref WaveFormat pwfx,
IntPtr dwCallback,
IntPtr dwInstance,
WaveInterop.WaveInOutOpenFlags fdwOpen
);

在C#代码中声明了一个实现于winmm.dll的waveOutOpen函数,从而调用Windows API提供的这些与音频相关的函数

P/Invoke#

互操作中最常见的一种,通过DllImport引入并调用原生DLL中的C风格函数

[DllImport("user32.dll", CharSet = CharSet.Unicode)]
static extern int MessageBox(IntPtr hWnd, string text, string caption, uint type);
MessageBox(IntPtr.Zero, "Hello world!", "mbox title", 0);

注意事项

  • 原生C指针用IntPtr,随平台改变长度
  • 实际调用的函数不一定完全一样,CharSet.Unicode则会调用MessageBoxW而非我们定义的MessageBox(Windows API知识,从下面的写法也可以看出)
  • 字符串可以直接用string而不用神秘字符数组/指针,赞美C#!

然而这种方法在第一次执行时较慢,因为需要CLR在运行时生成IL Stub,即一些动态代码用来完成C#类型(比如string)到原生类型(比如wchar_t*)的转换
另一种等效的写法:手动导入函数地址

[UnmanagedFunctionPointer(CallingConvention.Winapi, CharSet = CharSet.Unicode)]
delegate int MessageBoxDelegate(IntPtr hWnd, string text, string caption, uint type);
var lib = NativeLibrary.Load("user32.dll");
var addr = NativeLibrary.GetExport(lib, "MessageBoxW");
var MessageBox = Marshal.GetDelegateForFunctionPointer<MessageBoxDelegate>(addr);
MessageBox(IntPtr.Zero, "hello", "mbox title", 0);

这种写法可以把耗时的导入过程(字符串查表、委托创建)手动移到程序启动时(例如静态构造函数中),防止阻塞后续的业务代码。
为了彻底地优化性能,从.NET 7+起我们有了LibraryImport,以源生成器的方式替代运行时生成的IL Stub
只需将定义改为

[LibraryImport("user32.dll", StringMarshalling = StringMarshalling.Utf16)]
private static partial int MessageBoxW(IntPtr hWnd, string text, string caption, uint uType);

就可以获得零运行时反射、零动态生成的代码,于是也就适用于C#性能优化的最高的山NativeAOT(

然而注意到这里函数名写了MessageBoxW(或者在LibraryImportAttribute的EntryPoint属性手动指出),因为源生成器不支持自动推断后缀,具体原因如下

  • LibraryImport是为 NativeAOT 场景设计的。AOT编译器需要在编译时就知道所有原生调用的确切目标,以便静态链接或生成确切的导入表。字符集信息只有在运行时才能获取,在AOT的静态世界里是无法实现的。
  • 官方设计文档指出,在生成的代码中执行平台检查,违背了“按需付费”原则。这意味着,不应该为所有P/Invoke都无条件加入一个运行时平台判断的开销。
  • EntryPoint的自动后缀推断是Win32编程的历史遗留特性,具有很强的Windows色彩。LibraryImport的设计目标之一是跨平台,因此将这种平台特定的隐式规则移除了。

文章分享

如果这篇文章对你有帮助,欢迎分享给更多人!

C# 反射与互操作
https://blog.truebigsand.top/posts/csharp-reflection-and-interop/
作者
真-大沙子
发布于
2026-10-30
许可协议
CC BY-NC-SA 4.0

评论区

Profile Image of the Author
真-大沙子
编程 · 数学 · 二次元 · 生活
公告
分类
标签
站点统计
文章
48
分类
5
标签
57
总字数
46,274
运行时长
0 天
最后活动
0 天前
站点信息
构建平台
GitHub Actions
博客版本
Firefly v6.16.8
文章许可
CC BY-NC-SA 4.0
文章目录