简体   繁体   中英

Get a class method that implements an interface defined in a different DLL

My case is a little complicated, so I am explaining it with an example.

Here is my case:

fileA.cs :

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

Note : fileA.cs will be compiled to 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;
        }
    }
}

Note : fileB.cs will be compiled to fileB.dll .

Now I have 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?
    }
}

There is an answer here ( 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));

But it seems not be able to work in my case.

Well, seeing as you already have the assembly available right there as 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM