获取实现在另一个DLL中定义的接口的类方法
本文关键字:定义 接口 类方法 DLL 实现 另一个 获取 | 更新日期: 2023-09-27 18:08:06
我的情况有点复杂,所以我用一个例子来解释。
这是我的例子:
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;