2013-01-31 30 views
0

假設我有一個interface稱爲IVerifier思考問題

public interface IVerifier 
{ 
    bool Validate(byte[]x, byte[]y); 
} 

,我不得不通過反射加載程序集,並裝配擁有相同的簽名,這是怎麼可能做到這一點:

IVerifier c = GetValidations(); 
c.Validate(x,y); 

而且裏面的GetValidations()是反射駐留!

我一直在想這個問題,我得到的只是調用反射方法將會在GetValidations()之內,但它必須要像上面那樣去做。

+0

程序集有類實現接口嗎? –

+0

使用Assembly.CreateInstance()方法創建實現IVerifier的類的對象。你需要很好地猜測實現它的類的名字。或者迭代程序集中的類型以找到實現該接口的類型。或者使用工廠方法。或者使用像MEF這樣的插件框架。等等。 –

+0

該程序集包含什麼內容?實現接口的類型?或者只是鍵入具有相同簽名的方法?你知道你想使用的類型的名稱(可能是方法)嗎? – svick

回答

1

假設你不知道你想在另一個組件實例的類型,你只知道它實現IVerifier你可以使用這樣的方法:

static TInterface GetImplementation<TInterface>(Assembly assembly) 
{ 
    var types = assembly.GetTypes(); 
    Type implementationType = types.SingleOrDefault(t => typeof (TInterface).IsAssignableFrom(t) && t.IsClass); 


    if (implementationType != null) 
    { 
     TInterface implementation = (TInterface)Activator.CreateInstance(implementationType); 
     return implementation; 
    } 

    throw new Exception("No Type implements interface.");  
} 

使用示例:

using System; 
using System.Linq; 
using System.Reflection; 

namespace ConsoleApplication9 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      IHelloWorld x = GetImplementation<IHelloWorld>(Assembly.GetExecutingAssembly()); 

      x.SayHello(); 
      Console.ReadKey(); 

     } 
     static TInterface GetImplementation<TInterface>(Assembly assembly) 
     { 
      var types = assembly.GetTypes(); 
      Type implementationType = types.SingleOrDefault(t => typeof (TInterface).IsAssignableFrom(t) && t.IsClass); 


      if (implementationType != null) 
      { 
       TInterface implementation = (TInterface)Activator.CreateInstance(implementationType); 
       return implementation; 
      } 

      throw new Exception("No Type implements interface."); 

     } 
    } 
    interface IHelloWorld 
    { 
     void SayHello(); 
    } 
    class MyImplementation : IHelloWorld 
    { 
     public void SayHello() 
     { 
      Console.WriteLine("Hello world from MyImplementation!"); 
     } 
    } 

} 
+0

偉大的答案,精彩的解釋,應該被標記爲已回答並擁有+1 – SVI