2013-02-21 189 views
3

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

为了澄清>如果有人记录有像这样它的属性的方法:

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

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

Signature: 

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

你是问关于编码您自己的属性,它需要的参数,或者您希望通过反射办法,找出别人的属性已建成的? – dasblinkenlight 2013-02-21 22:58:13

+0

通过反思别人的属性被构建的方式 – 2013-02-21 23:05:40

+0

嗯,谢谢澄清。我很抱歉误解你的问题。我的方法显然不会这样做。你可能不得不检查IL,但我不知道如何去这样做。 – 2013-02-21 23:13:04

回答

5

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

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"); 
+0

关于班级属性呢?会员部分很容易。我还没有想出如何反思类级属性参数。 – jwize 2014-02-18 06:04:42

3

对于ComVisibileAttribute,传递给构造函数的参数变成​​属性。

[ComVisibleAttribute(true)] 
public class MyClass { ... } 

... 

Type classType = typeof(MyClass); 
object[] attrs = classType.GetCustomAttributes(true); 
foreach (object attr in attrs) 
{ 
    ComVisibleAttribute comVisible = attr as ComVisibleAttribute; 
    if (comVisible != null) 
    { 
     return comVisible.Value // returns true 
    } 
} 

其他属性将采用类似的设计模式。


编辑

我发现this articleMono.Cecil描述如何做一些非常相似。这看起来应该做你需要的。

foreach (CustomAttribute eca in classType.CustomAttributes) 
{ 
    Console.WriteLine("[{0}({1})]", eca, eca.ConstructorParameters.Join(", ")); 
} 
相关问题