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

标签 c# reflection pdb-files

我正在开发文档生成器。 MSDN 文档显示了应用时传递给属性的参数。如 [ComVisibleAttribute(true)]。我如何通过反射、pdb 文件或其他方式获取那些参数值和/或在我的 C# 代码中调用的构造函数?

澄清>如果有人记录了一个方法,它有一个属性,就像这样:

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

我希望能够像这样在我的文档中显示方法的签名:

Signature:

[SomeCustomAttribute("a supplied value")]
void Foo();

最佳答案

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

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);
    }
}

要获取成员,首先要获取类型。有两种获取类型的方法。

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

然后你可以找到,例如,一个特定的方法。看reflection documentation了解更多信息。

MemberInfo member = typeof(MyType).GetMethod("Foo");

关于c# - 如何获取传递给属性构造函数的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15013794/

相关文章:

c# - Microsoft 依赖注入(inject)和逆变

c# - 在 C# 中将 float 保存到二进制文件并在 C 中打开

c# - 尝试让委托(delegate)关联到控件的事件时出现问题

oracle - 有关 PL/SQL 包级记录类型的元数据

security - 将 pdb 与 exe 一起发布有多安全?

c# - 使用正则表达式和 C# 拆分字符串并添加到列表

c# - 制作可换肤的用户界面组件的次优方法是什么?

C# - 如何使用反射调用参数数量可变的静态方法

c++ - 如何编译以便文件名/行号可用于错误报告工具?

asp.net-mvc - Glimpse.AspNet.pdb 未加载