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

如何获取C# Source Generator所分析程序集的完整文件路径?

C# Source Generator 获取被分析程序集完整路径解决方案

你在Compilation属性中找不到对应路径是正常的,程序集输出路径属于MSBuild构建流程的配置项,不属于编译语义模型的固有属性,需要通过MSBuild属性传递的方式获取,具体操作如下:

步骤1:配置项目文件传递构建属性

修改待分析项目的.csproj文件,声明要将MSBuild的内置属性TargetPath(对应最终输出程序集的完整路径)传递给Source Generator:

<Project>
  <!-- 已有配置保持不变 -->
  <PropertyGroup>
    <CompilerVisibleProperty Include="TargetPath" />
  </PropertyGroup>
</Project>

如果需要获取编译阶段生成的中间程序集路径,可将TargetPath替换为IntermediateAssembly。

步骤2:在Generator代码中读取路径

适配IIncrementalGenerator(增量生成器,推荐)

[Generator]
public class CustomGenerator : IIncrementalGenerator
{
    public void Initialize(IncrementalGeneratorInitializationContext context)
    {
        // 注册读取全局构建属性
        var outputPathProvider = context.AnalyzerConfigOptionsProvider
            .Select((options, _) => 
            {
                options.GlobalOptions.TryGetValue("build_property.TargetPath", out var targetPath);
                return targetPath;
            });

        // 关联生成逻辑
        context.RegisterSourceOutput(outputPathProvider, (sourceContext, targetPath) =>
        {
            if (string.IsNullOrEmpty(targetPath)) return;
            // 此处targetPath即为被分析程序集的完整文件路径,可直接用于业务逻辑
        });
    }
}

适配ISourceGenerator(传统生成器)

在Execute方法中直接读取属性即可:

public void Execute(GeneratorExecutionContext context)
{
    context.AnalyzerConfigOptions.GlobalOptions.TryGetValue("build_property.TargetPath", out var targetPath);
    // 后续业务逻辑
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 10:45:03