从 INamedTypeSymbol.GetAttributes() 即 AttributeData 对象获取属性对象? [英] Get Attribute object from INamedTypeSymbol.GetAttributes() i.e. AttributeData object?
问题描述
我已经定义了以下属性
[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 { }
一个指向 Program
类的 INamedTypeSymbol
变量 namedTypeSymbol
提供给我,我设法获得了属性的名称.
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") { ... }
}
但是我如何访问设置为 SomeInfo
的内容?
But how do I access what was set as SomeInfo
?
推荐答案
有两种方法可以将参数传递给属性.通过设置属性 ([Demo(SomeInfo="hello world")]
) 或通过构造函数,正如您所做的那样.如果您使用命名方法,Ponas 将是正确的,解决方案在于 NamedArguments
.
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
.
但是,当您使用构造函数时,数据位于ConstructorArguments
中.这是一个TypedConstant
的数组,从中可以得到值"hello world"
:
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;
这篇关于从 INamedTypeSymbol.GetAttributes() 即 AttributeData 对象获取属性对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!