2014-01-06 18 views
0

我正在執行Apache Thrift,所有thrift生成的服務類都包含一個名爲Iface的嵌套接口。使用反射來查找包含接口名稱的程序集中的所有類

我有一些額外的代碼,它採用節儉生成的內容並基於命名約定構建頁面對象模式。

我需要做的是,使用反射枚舉生成的程序集中所有具有名爲Iface的嵌套接口的類。

所有這些代碼以前都是通過protobuf.net和Google協議緩衝區實現的,我們正在開發更加一致的多語言支持。

隨着protobuf的實現,我們用這條線找到正確的服務:

_inputDll.GetTypes().Where(x => typeof(IService).IsAssignableFrom(x) && x.Name != "Stub") 

這種結構將不再有效,因爲沒有一個確定節儉內接口。

這裏是產生的節儉的一個例子,我試圖尋找代碼:

public partial class ServiceA { 
    public interface Iface { 
     Thrift.ActionResult SetupPreferences(Thrift.BillingPreferencesInfo info); 
    } 
    // Thrift implementations 
} 

public partial class ServiceB { 
    public interface Iface { 
     Thrift.ActionResult SetupAddress(Thrift.AddressInfo info); 
    } 
    // Thrift implementations 
} 
+0

具體這個實現我沒有嘗試過任何東西,因爲我不知道如何着手,因爲這是我沒有訪問得到的類型,多種不同的接口,我要添加這個問題的更多細節。 – Phaeze

+0

通過「嵌套接口」,你真的是指在一個類的範圍內的接口聲明,或者你使用單詞「嵌套」而不是「實現」?你最好提供一個樣本班。 –

+0

不,我真的是指在一個類中聲明的接口。它是我遇到的節儉的一個缺點。 – Phaeze

回答

1

源類提供的是這樣的:

public class SomeClass 
{ 
    public interface IFace { … } 
} 

那麼你的查詢需要利用Type.GetNestedType(),像這樣:

+1

真棒,乍一看這應該工作將盡快接受我測試它。謝謝。 – Phaeze

0

試試這個,它有點舊的代碼,但我牛逼的作品:

public static System.Collections.Generic.List<Type> GetTypesImplementingInterface(string interfaceTypeName, string assembliesNameStartWith) 
    { 
     var returnTypes = new System.Collections.Generic.List<Type>(); 

     var list = BuildManager.GetReferencedAssemblies().Cast<Assembly>().Where(referencedAssembly => referencedAssembly.FullName.StartsWith(assembliesNameStartWith, StringComparison.InvariantCultureIgnoreCase)).ToList(); 

     try 
     { 
      returnTypes.AddRange(
       from ass in list 
       from t in ass.GetTypes() 
       where (TypeImplementsInterface(t, interfaceTypeName)) 
       select t 
      ); 
     } 
     catch (Exception ex) 
     { 
      Trace.TraceWarning("GetTypesImplementingInterface:{0}:interfaceTypeName:{1}:assembliesNameStartWith:{2}", 
           ex.ToString(), interfaceTypeName, assembliesNameStartWith); 
      returnTypes = new System.Collections.Generic.List<Type>(); 
     } 
     return returnTypes; 
    } 


    private static bool TypeImplementsInterface(Type theType, string interfaceName) 
    { 
     Type interFaceType = theType.GetInterface(interfaceName, true); 
     return (interFaceType != null); 
    } 
+0

問題是我正在尋找的類沒有實現任何接口 – Phaeze

+0

哦!你說得對,我想念你的問題。 –

+0

'從t中開始ass.GetTypes()'...這真的返回了什麼? :) – jebar8

相關問題