gpt4 book ai didi

c# - 动态加载程序集

转载 作者:行者123 更新时间:2023-11-30 23:18:40 24 4
gpt4 key购买 nike

在过去,我编写了一个应用程序,它根据数据库中的值动态加载 DLL 及其所有依赖项,如下所示(清除了一些参数)

VB

Dim oType As System.Type
Dim oAssembly As System.Reflection.Assembly
Dim oObject As System.Object
oAssembly = Assembly.LoadFrom(path)
oType = oAssembly.GetType("LogicValidator")
oObject = Activator.CreateInstance(oType)

oObject.Initialise("param1", "param2", "param3", AuditTrail, UserInfo, workingDir)
Console.WriteLine("Begin processing...")
oObject.ProcessBatch(cm_uid)

现在,当我用 C# 编写类似的东西时,在构建应用程序之前出现错误,说明如下:

C#

System.Type oType = default(System.Type);
System.Reflection.Assembly oAssembly = default(System.Reflection.Assembly);
System.Object oObject = null;
oAssembly = Assembly.LoadFrom(path);
oType = oAssembly.GetType("LogicValidator");
oObject = Activator.CreateInstance(oType);
oObject.Initialise("param1", "param2", "param3", AuditTrail, UserInfo, workingDir);
Console.WriteLine("Begin processing...");
oObject.ProcessBatch(cm_uid);

错误

'object' does not contain a definition for 'Initialise' and no extension method 'Initialise' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

如果某个方法是在运行时加载的,我的 C# 应用程序如何在编译前识别该方法不存在?

编辑

为了帮助其他遇到这个问题的人,我删除了以下内容。虽然它确实指出了答案,但其他人的回答更为 Eloquent 。 :-)

我想补充一点,下面的工作 - 但前提是加载的程序集依赖项已经存在。

var DLL = Assembly.LoadFile(path);
Type type = DLL.GetType("LogicValidator");
dynamic c = Activator.CreateInstance(type);
c.Initialise("param1", "param2", "param3", audit, UserInfo, workingDir);
Console.WriteLine("Begin processing...");
c.ProcessBatch(cm_uid);

最佳答案

如果您在编译时不知道类型,您可以通过将类型声明为 dynamic 来使用动态运行时:

var oAssembly = Assembly.LoadFrom(path);
var oType = oAssembly.GetType("LogicValidator");
dynamic oObject = Activator.CreateInstance(oType);
oObject.Initialise("param1", "param2", "param3", AuditTrail, UserInfo, workingDir);
Console.WriteLine("Begin processing...");
oObject.ProcessBatch(cm_uid);

但是,您可能会考虑一种方法,其中加载的类型实现已知接口(interface)(该接口(interface)将在加载项和您的代码都引用的程序集中声明):

public interface IProcessor
{
void Initialise(
string param1,
string param2,
string param2,
AuditTail auditTrail,
UserInfo userInfo,
DirectoryInfo workingDir);

void ProcessBatch(int uid);
}

然后您可以按如下方式创建实例并获得完整的 IntelliSense 支持和类型检查:

var oAssembly = Assembly.LoadFrom(path);
var oType = oAssembly.GetType("LogicValidator");
IProcessor oObject = Activator.CreateInstance(oType);
oObject.Initialise("param1", "param2", "param3", AuditTrail, UserInfo, workingDir);
Console.WriteLine("Begin processing...");
oObject.ProcessBatch(cm_uid);

关于c# - 动态加载程序集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40743536/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com