Question as in the title.
From an object of type AttributeSyntax
how can I get the related AttributeData
representation in order to access the metadata?
你需要找到ISymbol
的语法被应用到,打电话GetAttributes()
并找到返回AttributeData
为其ApplicationSyntaxReference
您匹配AttributeSyntax
。
@SLaks answer is correct. Here is some code to retrieve attributes from a 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);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.