2016-09-21 76 views
0

我的情況有點複雜,所以我用一個例子來解釋它。獲取一個類方法,實現在不同的DLL中定義的接口

這裏是我的情況:

fileA.cs

namespace companyA.testA 
{ 
    public interface ITest 
    { 
     int Add(int a, int b); 
    } 
} 

注意fileA.cs將被編譯到fileA.dll

fileB.cs

namespace companyA.testB ////note here a different namespace 
{ 
    public class ITestImplementation: ITest 
    { 
     public int Add(int a,int b) 
     { 
      return a+b; 
     } 
    } 
} 

備註fileB.cs將編譯爲fileB.dll

現在我有run.cs

using System.Reflection; 

public class RunDLL 
{ 
    static void Main(string [] args) 
    { 
     Assembly asm; 
     asm = Assembly.LoadFrom("fileB.dll"); 

     //Suppose "fileB.dll" is not created by me. Instead, it is from outside. 
     //So I do not know the namespace and class name in "fileB.cs". 
     //Then I want to get the method "Add" defined in "fileB.cs" 
     //Is this possible to do? 
    } 
} 

這裏有一個答案(Getting all types that implement an interface):

//answer from other thread, NOT mine: 
var type = typeof(IMyInterface); 
var types = AppDomain.CurrentDomain.GetAssemblies() 
    .SelectMany(s => s.GetTypes()) 
    .Where(p => type.IsAssignableFrom(p)); 

,但它似乎無法在我的情況下工作。

+0

你最後的代碼示例使用IMyInterface的,但這並不與前面的例子任何關聯。 –

+0

@JonathonChase最後的代碼不是我的。在發生混淆的情況下添加評論。謝謝。 – derek

+0

@derek所以而不是IMyInterface它將是var type = typeof(ITest); ? – TlonXP

回答

0

嘛,看到你已經擁有那裏作爲asm大會:

var typesWithAddMethod = 
     from type in asm.GetTypes() 
     from method in type.GetMethods(BindingFlags.Public|BindingFlags.Instance|BindingFlags.DeclaredOnly) 
     where method.Name == "Add" 
     select type; 
相關問題