簡體   English   中英

獲取實現在不同DLL中定義的接口的類方法

[英]Get a class method that implements an interface defined in a different 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?
    }
}

這里有一個答案( 獲取實現接口的所有類型 ):

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

但這似乎無法解決我的問題。

好吧,看到您已經有了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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM