【发布时间】:2010-12-17 17:13:21
【问题描述】:
我需要在 C# 中调用一个函数来调用用户的 dll。
例如,当用户使用 ABC 类创建 abc.dll 时,我想加载该 dll 以运行该类中的方法 xyz(a)。
object plugInObject = node.GetPlugInObject("abc.dll", "ABC");
plugInObject.runMethod("xyz", "a");
如何在 C# 中实现这些功能?
添加
这是插件代码,dll复制为plugin/plugin.dll。
namespace HIR
{
public class PlugIn
{
public int Add(int x, int y)
{
return (x + y);
}
}
}
这是调用这个插件的那个。
using System;
using System.Reflection;
class UsePlugIn
{
public static void Main()
{
Assembly asm = Assembly.LoadFile("./plugin/plugin.dll");
Type plugInType = asm.GetType("HIR.PlugIn");
Object plugInObj = Activator.CreateInstance(plugInType);
var res = plugInType.GetMethod("Add").Invoke(plugInObj, new Object[] { 10, 20 });
Console.WriteLine(res);
}
}
【问题讨论】:
-
了解反射,动态 dll 加载
-
这些 *.dll 文件是 .NET 程序集还是本机库?
-
根据插件实现,没有与 GetMethod() 一起使用的方法“Abc”。
-
PlugIn 类应该是公开的。如果没有修饰符,默认情况下它声称是内部的。
-
@peo:没错。我改变了它。谢谢。
标签: c# reflection plugins