2013-02-21 102 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(", ")); 
} 
相關問題