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?
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?
You need to find the ISymbol
that the syntax is applied to, call GetAttributes()
, and find the returned AttributeData
for which ApplicationSyntaxReference
matches your 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);
}
}
Compilation.Assembly.GetAttributes()
. –
Eyeleteer © 2022 - 2024 — McMap. All rights reserved.