我正在开发文档生成器。 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);
}
}
要获取成员,首先要获取类型。有两种获取类型的方法。
- 如果您有实例
obj
,请调用Type type = obj.GetType();
。 - 如果您有类型名称
MyType
,请执行Type type = typeof(MyType);
。
然后你可以找到,例如,一个特定的方法。看reflection documentation了解更多信息。
MemberInfo member = typeof(MyType).GetMethod("Foo");
关于c# - 如何获取传递给属性构造函数的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15013794/