gpt4 book ai didi

c# - 加载程序集、查找类和调用 Run() 方法的正确方法

转载 作者:IT王子 更新时间:2023-10-29 03:39:26 25 4
gpt4 key购买 nike

示例控制台程序。

class Program
{
static void Main(string[] args)
{
// ... code to build dll ... not written yet ...
Assembly assembly = Assembly.LoadFile(@"C:\dyn.dll");
// don't know what or how to cast here
// looking for a better way to do next 3 lines
IRunnable r = assembly.CreateInstance("TestRunner");
if (r == null) throw new Exception("broke");
r.Run();

}
}

我想动态构建一个程序集(.dll),然后加载该程序集,实例化一个类,并调用该类的Run()方法。我应该尝试将 TestRunner 类转换为某种东西吗?不确定一个程序集(动态代码)中的类型如何知道我的(静态程序集/外壳应用程序)中的类型。仅使用几行反射代码来仅在一个对象上调用 Run() 是否更好?该代码应该是什么样的?

更新:威廉·埃德蒙森 - 查看评论

最佳答案

使用 AppDomain

将程序集加载到自己的中更安全、更灵活AppDomain首先。

所以不是 the answer given previously :

var asm = Assembly.LoadFile(@"C:\myDll.dll");
var type = asm.GetType("TestRunner");
var runnable = Activator.CreateInstance(type) as IRunnable;
if (runnable == null) throw new Exception("broke");
runnable.Run();

我建议如下(改编自 this answer to a related question ):

var domain = AppDomain.CreateDomain("NewDomainName");
var t = typeof(TypeIWantToLoad);
var runnable = domain.CreateInstanceFromAndUnwrap(@"C:\myDll.dll", t.Name) as IRunnable;
if (runnable == null) throw new Exception("broke");
runnable.Run();

现在您可以卸载程序集并进行不同的安全设置。

如果您想要动态加载和卸载程序集的更多灵 active 和功能,您应该查看托管加载项框架(即 System.AddIn 命名空间)。有关详细信息,请参阅有关 Add-ins and Extensibility on MSDN 的文章.

关于c# - 加载程序集、查找类和调用 Run() 方法的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1137781/

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