You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#程序中如何通过ILSpy反编译获取指定类的源代码?

基于新版ILSpy获取指定类型C#源代码的实现方案

旧版ILSpy示例中提到的AssemblyDefinition、CSharpLanguage、DecompilationOptions等类型在8.0及以后版本中已经被完全重构,直接照搬旧代码会找不到类型,按以下步骤实现即可正常运行:

前置依赖

  • 在项目中通过NuGet安装ICSharpCode.Decompiler 8.0以上稳定版本即可,不需要手动引入零散DLL,安装完成后会自动加载所有所需的命名空间依赖。

完整实现代码

首先引入所需命名空间:

using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.CSharp;
using ICSharpCode.Decompiler.TypeSystem;
using System;
using System.Reflection;
using System.IO;

实现GetSourceCode方法:

public static string GetSourceCode(Type targetType)
{
    if (targetType == null)
        throw new ArgumentNullException(nameof(targetType));

    Assembly targetAssembly = targetType.Assembly;
    // 初始化反编译配置,可按需调整输出规则
    var settings = new DecompilerSettings
    {
        ThrowOnAssemblyResolveErrors = false,
        UseDebugSymbols = false, // 无对应PDB文件时设为false避免报错
        RemoveDeadCode = true,
        UseFileScopedNamespaces = true // 按C# 10+格式输出文件范围命名空间,不需要可设为false
    };

    CSharpDecompiler decompiler;
    // 兼容磁盘程序集和内存动态程序集
    if (!string.IsNullOrEmpty(targetAssembly.Location))
    {
        decompiler = new CSharpDecompiler(targetAssembly.Location, settings);
    }
    else
    {
        // 动态生成/内存加载的无磁盘路径程序集,需传入程序集原始字节数组
        // 可根据实际场景获取程序集对应的byte[]传入
        byte[] assemblyBytes = ReadAssemblyBytes(targetAssembly);
        decompiler = new CSharpDecompiler(assemblyBytes, new ModuleReference(targetAssembly.FullName), settings);
    }

    // 按类型全限定名反编译,自动支持泛型、嵌套类型
    var fullTypeName = new FullTypeName(targetType.FullName ?? throw new InvalidOperationException("目标类型无有效全限定名"));
    return decompiler.DecompileTypeAsString(fullTypeName);
}

调用方式

直接传入目标类型的Type对象即可,比如获取示例中Foo类的源码:

string sourceCode = GetSourceCode(typeof(Foo));

返回结果就是Foo类的完整格式化C#源代码,和预期输出一致。

常见配置说明

  • 如果需要调整反编译输出格式,直接修改DecompilerSettings的对应属性即可:比如设置ShowXmlDocumentation = true可以输出类型和成员的XML注释,FullyQualifyAmbiguousTypeNames = true会给重名类型加全限定命名空间。
  • 如果需要反编译整个程序集的代码,直接调用decompiler.DecompileWholeModuleAsString()即可。
  • 如果目标类型依赖其他程序集,反编译器会自动按当前应用程序域的程序集加载规则解析依赖,不需要手动加载。

内容的提问来源于stack exchange,提问作者CaptainDucko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.03 10:45:39