2013-04-10 46 views
-1

我正在開發C#/。NET 3.5應用程序(並希望保留在該版本的.NET),並且無法計算如何使用反射來解決此問題。我找到了解決方法,但不是「整潔」。 代碼如下,我需要發現所有的接口實現,以便將來當添加更多的接口實現時,我不需要更改現有的代碼。如何使用反射來解決這個....? (C#/。NET)

interface Ii { } 
class A : Ii { } 
class A1 : A { } 
class A2 : A { } 
class A3 : A { } 
class B : Ii { } 
class C : Ii{ } 
// maybe in future class D : Ii { } 
// maybe in future class E : Ii { } 

class Helper 
{ 
    static List<Type> GetAllInterfaceImplemenations() 
    {// do reflection magic and return ["A1","A2","A3","B","C"] ... 
    // I will use this method to fill comboBox-es , create objects factory, etc... 
    // there should be no changes if/when in future I add class D etc. 
    } 
} 
+1

既然你想使用類型,你不應該使用ArrayList。最好用列表 CSharpie 2013-04-10 17:31:35

+0

這裏有個類似的問題,你可以看看我的答案有:http://stackoverflow.com/questions/13994579/how-can-i-use-reflection-or-alternative-to -create-function-calls-programatically/13994668#13994668 – user287107 2013-04-10 17:29:54

回答

5

嘗試這種情況:

public static List<string> GetAllInterfaceImplemenations() 
{ 
    var interfaceType = typeof(Ii); 
    var list = new List<string>(); 
    foreach (var type in Assembly.GetExecutingAssembly().GetTypes()) 
    { 
     if (type.IsClass && interfaceType.IsAssignableFrom(type)) 
     { 
      list.Add(type.Name); 
     } 
    } 

    return list; 
} 
+0

-1對於Arraylist – CSharpie 2013-04-10 17:33:08

+1

好吧修復它。現在我們使用列表。 – Dan 2013-04-10 17:37:48

+0

我想要字符串列表(ClassNames),但這沒有問題。 – 2013-04-10 18:13:36

0

問題的上述方案是這樣它會返回類「A」從上面的例子,這是不想要的。只需要「楓葉」。但是,上面的解決方案給出瞭如何解決它的想法。所以,這裏是我的製作解決方案(對不起,ArrayList是我最喜歡的集合...)。

private static ArrayList GetAllInterfaceImplemenations() 
{ 
    ArrayList listOfLeafsNames = null; 
    try 
    { 
     Type interfaceType = typeof(ISpeechCodec); 
     ArrayList listOfAll = new ArrayList(); 
     foreach (Type type in Assembly.GetExecutingAssembly().GetTypes()) 
     { 
      if (type.IsClass && interfaceType.IsAssignableFrom(type)) 
      { 
       listOfAll.Add(type); 
      } 
     } 

     listOfLeafsNames = new ArrayList(); 
     foreach (Type typeCandidate in listOfAll) 
     { 
      bool isLeaf = true; 
      foreach (Type type2 in listOfAll) 
      { 
       if (!(typeCandidate.Equals(type2))) 
       { 
        if (typeCandidate.IsAssignableFrom(type2)) 
        { 
         isLeaf = false; 
        } 
       } 
      } 
      if (isLeaf) 
      { 
       listOfLeafsNames.Add(typeCandidate.FullName); 
      } 
     } 
    } 
    catch (Exception ex) 
    { 
     Setup_TraceExceptions(ex.ToString()); 
    } 

    return listOfLeafsNames; 
} 
+0

如何將A級標記爲抽象?這將是區分不應該創建的類和應該創建的類的乾淨方式 – user287107 2013-04-22 06:33:08