问题
I have defined the following attribute
[AttributeUsage(AttributeTargets.Class)]
class DemoAttribute : Attribute
{
public string SomeInfo { get; }
public DemoAttribute(string someInfo)
{
this.SomeInfo = someInfo;
}
}
which can be applied to some class as follows:
[Demo("hello world")]
class Program { }
An INamedTypeSymbol variable namedTypeSymbol pointing to the Program class is provided to me with which I managed to get the name of the attribute.
foreach(var attr in namedTypeSymbol.GetAttributes())
{
if(attr.AttributeClass.Name == "DemoAttribute") { ... }
}
But how do I access what was set as SomeInfo?
回答1:
There are two ways you can pass arguments to attributes. Either by setting the property ([Demo(SomeInfo="hello world")]) or via the constructor, as you are doing. If you used the named approach, Ponas would be correct that the solution lies in NamedArguments.
However, as you are using the constructor, the data is located in ConstructorArguments. This is an array of TypedConstant, from which you can get the value "hello world":
string attributeData = (string)attr.ConstructorArguments[0].Value;
来源:https://stackoverflow.com/questions/36919957/get-attribute-object-from-inamedtypesymbol-getattributes-i-e-attributedata-ob