Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从INamedTypeSymbol.GetAttributes()获取属性对象,即AttributeData对象?_C#_Roslyn - Fatal编程技术网

C# 从INamedTypeSymbol.GetAttributes()获取属性对象,即AttributeData对象?

C# 从INamedTypeSymbol.GetAttributes()获取属性对象,即AttributeData对象?,c#,roslyn,C#,Roslyn,我已经定义了以下属性 [AttributeUsage(AttributeTargets.Class)] class DemoAttribute : Attribute { public string SomeInfo { get; } public DemoAttribute(string someInfo) { this.SomeInfo = someInfo; } } 可应用于某些类别,如下所示: [Demo("hello world")] class Progr

我已经定义了以下属性

[AttributeUsage(AttributeTargets.Class)]
class DemoAttribute : Attribute
{
  public string SomeInfo { get; }

  public DemoAttribute(string someInfo)
  {
    this.SomeInfo = someInfo;
  }
}
可应用于某些类别,如下所示:

[Demo("hello world")]
class Program { }
向我提供了一个
INamedTypeSymbol
变量
namedTypeSymbol
,该变量指向
程序
类,我使用该类获取了属性的名称

foreach(var attr in namedTypeSymbol.GetAttributes())
{
  if(attr.AttributeClass.Name == "DemoAttribute") { ... }
}

但是如何访问设置为
SomeInfo

有两种方法可以将参数传递给属性。通过设置属性(
[Demo(SomeInfo=“hello world”)]
)或通过构造函数,就像您正在做的那样。如果使用命名方法,Ponas将正确地认为解决方案位于
NamedArguments

但是,在使用构造函数时,数据位于
ConstructorArguments
中。这是一个
TypedConstant
数组,从中可以获得值
“hello world”


有两种方法可以将参数传递给属性。通过设置属性(
[Demo(SomeInfo=“hello world”)]
)或通过构造函数,就像您正在做的那样。如果使用命名方法,Ponas将正确地认为解决方案位于
NamedArguments

但是,在使用构造函数时,数据位于
ConstructorArguments
中。这是一个
TypedConstant
数组,从中可以获得值
“hello world”


我真的不知道这是否有帮助(没有时间检查),但请尝试查看attr.NamedArguments属性。@PonasJustas没有办法将Roslyn类型(如
AttributeData
)转换为反射类型(如
Attribute
),这是正确的吗?@David correct。Roslyn和Reflection应该被视为两个不同的世界。有时它们具有类似的表示形式(如
MetadataName
),但据我所知,实际对象不会在任何地方进行转换。我不知道这是否有帮助(没有时间检查),但请尝试查看attr.NamedArguments属性。@PonasJustas没有“转换”的方法是正确的吗从Roslyn类型(如
AttributeData
)到反射类型(如
Attribute
),David更正。Roslyn和Reflection应该被视为两个不同的世界。有时它们有一个类似的表示形式(如
MetadataName
),但据我所知,实际对象不会在任何地方进行转换。
string attributeData = (string)attr.ConstructorArguments[0].Value;