繁体   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