2014-02-13 16 views
1

我寫了一個包含三種測試方法的C#單元測試項目'GameTest'。而且我還爲每種測試方法添加了一個自定義屬性'IDAttribute'。如何在未引用的程序集中提取方法的屬性值

public class IDAttribute : Attribute 
{ 
    public IDAttribute(int id) 
    { 
     ... 

在那之後,我寫了嘗試內的GameTest提取所有的測試方法的另一個應用

var x = Assembly.LoadFrom(@"GameTest.dll"); 
var types = x.GetTypes(); 

... 
foreach unit test method we found as m [Type:MethodInfo]: 
    var attrs = m.GetCustomAttributes(false); 
    foreach (var x in attrs) 
    { 
     if (x is TestCategoryAttribute) 
     { 
      var value = (x as TestCategoryAttribute).TestCategories; 
      Console.WriteLine(string.Join(", ", value); 
     } 
     else if (x is IDAttribute) 
     { 
      ... 

這裏的問題是,因爲沒有定義它,我不能寫「IDAttribute」直接[我有未引用GameTest.dll]。如果嘗試引用該dll,我們將無法獲得IDAttribute。

但是,在調試時,我可以看到使用Visual Studio 2010監視功能的ID值。

那麼,有沒有解決這個問題的方法?

+0

你可以嘗試引用超類。或者只是引用一個RawType ..但這將是無構造的,因爲你已經使用var了。 – Vogel612

+0

如果是這樣,我無法獲得IDAttribute中的值 – Jacky

回答

2

使用反射來獲取屬性類型和值:

foreach (var x in attrs) 
{ 
    var attributeType = x.GetType(); 
    if (attributeType.FullName == "ClassLibrary1.IDAttribute") // also check for attributeType.Assembly == loaded assembly, if needed 
    { 
     var id = (int)attributeType.GetProperty("ID").GetValue(x); 
     Console.WriteLine(id); 
    } 
} 
+1

或將其分配給一個'dynamic'變量。這消除了反思的需要。 – jessehouwing

2

由於PashaPash說,你可以使用反射來抓住「ID」值,或者您可以使用動態:

foreach (var x in attrs) 
{ 
    var attributeType = x.GetType(); 
    if (attributeType.FullName == "ClassLibrary1.IDAttribute") // also check for attributeType.Assembly == loaded assembly, if needed 
    { 
     dynamic idAttribute = x; 
     int id = idAttribute.ID; 
    } 
} 
相關問題