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
?
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;
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.