SourceGenerator:属性 ConstructorArguments 为空

Ric*_*ban 5 c# roslyn sourcegenerators

我正在编写一个源生成器,但正在努力获取传递给属性构造函数的参数值。

我将以下内容注入到编译中:

namespace Richiban.Cmdr
{
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public class CmdrMethod : System.Attribute
    {
        private readonly string _alias;

        public CmdrMethod(string alias)
        {
            _alias = alias;
        } 
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在我的示例应用程序中我有以下内容:

public static class InnerContainerClass
{
    [CmdrMethod("test")]
    public static void AnotherMethod(Data data)
    {
        Console.WriteLine($"In {nameof(AnotherMethod)}, {new { data }}");
    }
}

Run Code Online (Sandbox Code Playgroud)

编译时没有错误或警告,并且我成功地找到了用我的CmdrMethod属性修饰的所有方法,但我无法获取传递给属性的值,因为由于某种原因,该ConstructorArguments属性的属性为空:

private static ImmutableArray<string> GetAttributeArguments(
            IMethodSymbol methodSymbol,
            string attributeName)
{
    var attr = methodSymbol
        .GetAttributes()
        .Single(a => a.AttributeClass?.Name == attributeName);

    var arguments = attr.ConstructorArguments;
    
    if (methodSymbol.Name == "AnotherMethod")
        Debugger.Launch();

    return arguments.Select(a => a.ToString()).ToImmutableArray();
}
Run Code Online (Sandbox Code Playgroud)

查看 ConstructorArguments 属性如何为空

我是否误解了这个API?我究竟做错了什么?

You*_*f13 4

Compilation不可变的。当您添加属性的源代码时,您仍然有一个Compilation对属性一无所知的对象。这导致AttributeClass成为ErrorType@jason-malinowski 提到的。这对于这种源生成器来说是众所周知的,而且解决方案很简单。Compilation使用您注入的符号创建一个新的,然后SemanticModel从新的中获取 a Compilation

            // You should already have something similar to the following two lines.
            SourceText attributeSourceText = SourceText.From("CmdrMethod source code here", Encoding.UTF8);

            context.AddSource("CmdrMethod.g.cs" /* or whatever name you chose*/, attributeSourceText);

            // This is the fix.
            ParseOptions options = ((CSharpCompilation)context.Compilation).SyntaxTrees[0].Options;
            SyntaxTree attributeTree = CSharpSyntaxTree.ParseText(atttributeSourceText, (CSharpParseOptions)options);
            Compilation newCompilation = context.Compilation.AddSyntaxTrees(attributeTree);
            // Get the semantic model from 'newCompilation'. It should have the information you need.

Run Code Online (Sandbox Code Playgroud)

更新:从 3.9 包开始体验变得更好Microsoft.CodeAnalysis,您现在可以添加属性Initialize而不是Execute

        public void Initialize(GeneratorInitializationContext context)
        {
            // Register the attribute source
            context.RegisterForPostInitialization((i) => i.AddSource("CmdrMethod.g.cs", attributeText));
            // .....
        }
Run Code Online (Sandbox Code Playgroud)

然后,您可以直接使用您获得的编译Execute

请参阅自动通知示例