Get Attribute object from INamedTypeSymbol.GetAttributes() i.e. AttributeData object?

最后都变了- 提交于 2019-12-13 22:13:15

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!