源生成:使用具有 System.Type 类型参数的属性

问题描述 投票:0回答:1

在我的源生成器项目中,我有一个属性,它采用

System.Type
类型的参数。我能够获取作为字符串传入的类型的名称。我想知道是否可以在生成器中获取
System.Type
的实际实例?

我正在使用

IIncrementalGenerator
context.SyntaxProvider.ForAttributeWithMetadataName
来获取实际的目标节点。在第二个 lambda 中进行转换时,我试图获取
System.Type
实例。

示例代码:

public void Initialize(IncrementalGeneratorInitializationContext context)
{
    context.SyntaxProvider.ForAttributeWithMetadataName("Name.Of.AttributeAttribute", 
    (node, ct) => //filter logic
    (generatoraAttributeSyntaxContext, CancellationToken ct) =>
    {
        var nameOfPassedType = generatoraAttributeSyntaxContext.TargetSymbol.GetAttributes()[0].ConstructorArguments[0].Value.ToString()
        //Some further code
    }
}

我想要这样的东西:

public void Initialize(IncrementalGeneratorInitializationContext context)
{
    context.SyntaxProvider.ForAttributeWithMetadataName("Name.Of.AttributeAttribute", 
    (node, ct) => //filter logic
    (generatoraAttributeSyntaxContext, CancellationToken ct) =>
    {
        System.Type passedType = generatoraAttributeSyntaxContext. //Some further logic to actually acquire the type 
        //Some further code
    }
}

出于测试目的,代码片段假设属性和参数位于给定位置。

c# custom-attributes sourcegenerators incremental-generator
1个回答
0
投票

我就是这么做的。 我整理了一个关于源生成器的教程,您可以看一下。

https://github.com/WebbertSolutions/SourceGeneratorTutorial/tree/main/Tutorial

步骤 4 中的源代码最终就是您要查找的内容。 Generators\GenerateInterface.cs 是接口。

© www.soinside.com 2019 - 2024. All rights reserved.