2014-01-29 117 views
0

一般來說,函數類A有一個屬性Atr,我想要另一個類B,Type得到它在其中註冊的類Atr。 在我的情況下,它應該是Type = typeof(A)只有沒有A. 我希望你明白。感謝您的回答。如何通過屬性定義類型?

這裏是一個示例代碼。

public class Atr: Attribute 
{ 
    public Atr() 
    { 
     DefaultDescription = "hello"; 
     Console.WriteLine("I am here. I'm the attribute constructor!"); 
    } 

    public String CustomDescription { get; set; } 
    public String DefaultDescription { get; set; } 

    public override String ToString() 
    { 
     return String.Format("Custom: {0}; Default: {1}", CustomDescription, DefaultDescription); 
    } 
} 

class B 
{ 
    public void Laun() 
    { 
     Type myType = typeof(A); // хочу получить тоже самое только через Atr 
    } 
} 

class A 
{ 
    [Atr] 
    public static void func(int a, int b) 
    { 
     Console.WriteLine("a={0} b={1}",a,b); 
    } 
} 
+0

完全不清楚你在問什麼,你想檢查'func'方法是否有'Atr'屬性? –

+0

我想確定具有該屬性的類的類型。 例如,如果我調用任何具有屬性的類中的任何方法,請檢查Atr確定類型。 – askeet

回答

0

您可以使用大會反思,找出所有在他們的方法,裝飾用給定屬性的類:

看看在枚舉Assembly.GetTypes方法(http://msdn.microsoft.com/en-us/library/system.reflection.assembly.gettypes%28v=vs.110%29.aspx)給定裝配中的所有類型。

查看Type.GetMethods以枚舉給定類型中的所有公共方法(http://msdn.microsoft.com/en-us/library/424c79hc%28v=vs.110%29.aspx)。

然後最後,查看MemberInfo.CustomAttributes(http://msdn.microsoft.com/en-us/library/system.reflection.memberinfo.customattributes%28v=vs.110%29.aspx)以列出給定方法上的所有自定義屬性。 CustomAttributes的類型是CustomAttributeData,它具有屬性AttributeType,您可以對其進行比較。你可以根據你需要循環的事物數量(3個嵌套循環)猜測,它不容易,相當複雜,更不用說慢速,所以你可能想要裝飾你的類的一些其他方面,或者儘可能改變你的方法。例如,如果你修飾類本身,它會變得更容易一些:Find all classes with an attribute containing a specific property value

找到類類型的代碼最終看起來像這樣(沒有經過充分測試):

Type aType = null; 
foreach (Type t in Assembly.GetExecutingAssembly().GetTypes()) { 
    foreach (MethodInfo mi in t.GetMethods()) { 
    foreach (CustomAttributeData cad in mi.CustomAttributes) { 
     if (cad.AttributeType == typeof(Atr)) { 
     aType = t; 
     break; 
     } 
    } 
    } 
} 

if (aType == null) { 
    // not found 
} else { 
    // found and aType = typeof(A) in your exmaple 
} 

注意:你必須確保你列舉了正確的類型(參見類型類IsClass屬性) ,但爲了清晰起見,我將其留下。

希望這會有所幫助!

+0

Thansk的想法。也許你可以得到項目命名空間?搜索具有相對於它的屬性的類的方法? – askeet

相關問題