gpt4 book ai didi

c# - 如何使用新方法动态扩展 C# 类

转载 作者:太空宇宙 更新时间:2023-11-03 11:31:21 24 4
gpt4 key购买 nike

我正在 ASP.NET 中构建一个网站,该网站允许基于通用类创建新模块。新模块需要能够使用自己的方法/函数库扩展基类。我想在 Application_Start 加载所有模块。它们由唯一的字符串键标识。

结构是这样的:

root-Bin--module1.dll    --module2.dll-Modules--module1---mod.key1--module2---mod.key2

在启动时,每个模块文件夹都被读取并识别它的键,所有设置从数据库和公共(public)属性集加载,然后存储在一个集合中。当为模块请求页面时,基页面类使用它的唯一目录键加载适当的模块。问题是基本模块类不包含特定于该模块的方法库(只有它是从数据库加载的属性/设置)。我如何扩展模块类以在启动时加载模块期间包含方法,或者只是使用它的字符串名称动态实例化正确的扩展类?或任何其他想法?我不想在应用程序加载方法中对类名进行硬编码,以便它可以扩展以供将来添加的模块使用。

最佳答案

有几种方法可以做到这一点。一种方法是创建一个要继承的基类或接口(interface),在另一个 DLL 中编写您的后代类,然后使用 Assembly.LoadFrom() 方法从 DLL 加载适当的类,如需要。

public MyType LoadTypeFromAssembly(string assemblyPath, string typeName)
{
var assembly = Assembly.LoadFrom(assemblyPath);

if (assembly == null)
throw new InvalidOperationException("Could not load the specified assembly '" + assemblyPath + "'");

var type = assembly.GetType(typeName);
if (type == null)
throw new InvalidOperationException("The specified class '" + typeName + "' was not found in assembly '" + assemblyPath + "'");

var instance = (MyType)Activator.CreateInstance(type);
return instance;
}

MyType 是您的基类或接口(interface)的类型,typeName 是您的后代类的名称(继承自 MyType)。

关于c# - 如何使用新方法动态扩展 C# 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7670142/

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