如何获取传递给属性构造函数的参数?

Cha*_*ert 3 c# reflection pdb-files

我正在研究文档生成器.MSDN文档显示应用它们时传递给Attributes的参数.如[ComVisibleAttribute(true)].我如何通过反射,pdb文件或其他方式获取那些参数值和/或在我的c#代码中调用的构造函数?

澄清>如果有人记录了一个具有属性的方法,如下所示:

/// <summary> foo does bar </summary>
[SomeCustomAttribute("a supplied value")]
void Foo() {
  DoBar();
}
Run Code Online (Sandbox Code Playgroud)

我希望能够在我的文档中显示该方法的签名,如下所示:

Signature:

[SomeCustomAttribute("a supplied value")]
void Foo();
Run Code Online (Sandbox Code Playgroud)

Dan*_*ker 6

如果您有要获取自定义属性和构造函数参数的成员,则可以使用以下反射代码:

MemberInfo member;      // <-- Get a member

var customAttributes = member.GetCustomAttributesData();
foreach (var data in customAttributes)
{
    // The type of the attribute,
    // e.g. "SomeCustomAttribute"
    Console.WriteLine(data.AttributeType);

    foreach (var arg in data.ConstructorArguments)
    {
        // The type and value of the constructor arguments,
        // e.g. "System.String a supplied value"
        Console.WriteLine(arg.ArgumentType + " " + arg.Value);
    }
}
Run Code Online (Sandbox Code Playgroud)

要获得成员,请从获取类型开始.获取类型有两种方法.

  1. 如果您有实例obj,请致电Type type = obj.GetType();.
  2. 如果您有类型名称MyType,请执行Type type = typeof(MyType);.

然后你可以找到一个特定的方法.查看反射文档以获取更多信息.

MemberInfo member = typeof(MyType).GetMethod("Foo");
Run Code Online (Sandbox Code Playgroud)