[英]Get Attribute object from INamedTypeSymbol.GetAttributes() i.e. AttributeData object?
[英]How do I get AttributeData from AttributeSyntax in Roslyn?
题目如题。
从AttributeSyntax
类型的 object 如何获取相关的AttributeData
表示以访问元数据?
你需要找到ISymbol
的语法被应用到,打电话GetAttributes()
并找到返回AttributeData
为其ApplicationSyntaxReference
您匹配AttributeSyntax
。
@SLaks 的答案是正确的。 下面是一些从AttributeListSyntax
检索属性的代码:
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis;
using System.Collections.Generic;
static class Extensions
{
public static IReadOnlyList<AttributeData> GetAttributes(this AttributeListSyntax attributes, Compilation compilation)
{
// Collect pertinent syntax trees from these attributes
var acceptedTrees = new HashSet<SyntaxTree>();
foreach (var attribute in attributes.Attributes)
acceptedTrees.Add(attribute.SyntaxTree);
var parentSymbol = attributes.Parent!.GetDeclaredSymbol(compilation)!;
var parentAttributes = parentSymbol.GetAttributes();
var ret = new List<AttributeData>();
foreach (var attribute in parentAttributes)
{
if (acceptedTrees.Contains(attribute.ApplicationSyntaxReference!.SyntaxTree))
ret.Add(attribute);
}
return ret;
}
public static ISymbol? GetDeclaredSymbol(this SyntaxNode node, Compilation compilation)
{
var model = compilation.GetSemanticModel(node.SyntaxTree);
return model.GetDeclaredSymbol(node);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.