获取实现在不同DLL中定义的接口的类方法

时间:2016-09-21 23:27:46

标签: c# .net system.reflection

我的情况有点复杂,所以我用一个例子来解释它。

以下是我的案例:

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));

但似乎无法在我的情况下工作。

1 个答案:

答案 0 :(得分: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;