返回

c#-使用 Microsoft.CodeAnalysis,如何获取 Type 类型的 Attribute 属性的值?

发布时间:2022-06-28 07:44:08 435
# flask

我有一个Attribute类,用于修饰程序集以在C#源代码生成器中使用。我正在尝试获取System类型的一个参数的值。类型我可以很好地得到其他属性的值。

下面是属性类:

    [AttributeUsage(AttributeTargets.Assembly)]
    public class MigrationFunctionAttribute : Attribute
    {
        public Type MigrationFunction { get; set; }

        public string MigrationMethod { get; set; }
        public string DependsOn { get; set; }
        public string SqlScriptBucket { get; set; }
        // ATTRIBUTE:  ADD HERE
        public string Branch { get; set; }

    }

下面是我对该属性的用法:

[assembly: MigrationFunction(MigrationFunction = typeof(MigrationFunctions), MigrationMethod = nameof(MigrationFunctions.MyMigrator), Branch = "@Branch", DependsOn = "Restore")]

SyntaxReceiver,我尝试根据以下信息构建模型:

    public static AttributeModel2 Build(AttributeSyntax receiverMigrationFunctionAttribute, GeneratorExecutionContext context)
    {

        SemanticModel semanticModel = context.Compilation.GetSemanticModel(receiverMigrationFunctionAttribute.SyntaxTree);

        foreach (var attributeArgumentSyntax in receiverMigrationFunctionAttribute.ArgumentList.Arguments)
        {
            switch (attributeArgumentSyntax.NameEquals.Name.Identifier.ValueText)
            {
                case nameof(MigrationFunctionAttribute.MigrationFunction):


                    Debug.WriteLine(attributeArgumentSyntax.Expression);
                    // ^^^ outputs 'typeof(MigrationFunctions)'

                    TypeInfo t = semanticModel.GetTypeInfo(attributeArgumentSyntax.Expression);
                    Debug.WriteLine(t.Type.ToDisplayString());
                    // ^^^ outputs 'System.Type'


                    /// HOW DO I GET THE TYPE HERE, which should be "MigrationFunctions", not "System.Type"???
                    break;
                case nameof(MigrationFunctionAttribute.Branch):

                    var value = semanticModel.GetConstantValue(attributeArgumentSyntax.Expression);
                    Debug.WriteLine(value.Value);
                    // ^^^ outputs '@Branch just fine
                    break;

            }
        }
        
        return null;

    }

模型构建器方法可以按预期选择参数,但我无法弄清楚如何获取属性的正确类型信息:

public Type MigrationFunction { get; set; }

我得到System.Type了,而我期待得到MigrationFunctions。

当我输出时,我得到typeof(MigrationFunctions):

Debug.WriteLine(attributeArgumentSyntax.Expression);

如代码中所述,我如何在此处获取类型,应该是“MigrationFunctions”,而不是“System.Type”??

特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(0)
按点赞数排序
用户头像