GetSymbolInfo 在源生成器中返回属性的 null

GetSymbolInfo returning null for attribute in source generator

提问人:Gargoyle 提问时间:8/25/2023 更新时间:8/25/2023 访问量:23

问:

我正在尝试制作一个源生成器,该生成器根据类上设置的属性触发。我想获取用该属性修饰的类的名称,但是当我运行以下方法时,始终是.我知道当引用设置不正确时可能会发生这种情况,但我认为这里不会发生这种情况,因为显示了正确的项目。info.Symbolnullattribute

private static ClassDeclarationSyntax? GetSemanticTargetForGeneration(GeneratorSyntaxContext context) {
    if (context.Node is not ClassDeclarationSyntax classDeclarationSyntax)
        return null;

    foreach (var attributeList in classDeclarationSyntax.AttributeLists)
        foreach (var attribute in attributeList.Attributes) {
            var info = context.SemanticModel.GetSymbolInfo(attribute);
                
            if (info.Symbol is not INamedTypeSymbol symbol)
                continue;

            ...
        }

    return null;
}

我正在使用以下测试帮助程序类(带有 Verify.XUnit 20.8.1 和 Verify.SourceGenerators 2.1.0),其中我将程序集显式添加到编译的引用中。

public static Task Verify(string source) {
    var syntaxTree = CSharpSyntaxTree.ParseText(source);

    var references = new PortableExecutableReference[] {
        MetadataReference.CreateFromFile(typeof(LaMP.API.RepositoryAttribute).Assembly.Location)
    };

    var compilation = CSharpCompilation.Create("Test", new[] {
            syntaxTree
        }, references);

    var target = CSharpGeneratorDriver.Create(new RepositorySourceGenerator()).RunGenerators(compilation);
        
    return Verifier
        .Verify(target)
        .UseDirectory("Snapshots");
}
C# 代码生成 .NET-7.0 xunit.net C#-10.0

评论


答: 暂无答案