gpt4 book ai didi

c# - 从不同的程序集动态加载类(具有自定义行为)?

转载 作者:太空狗 更新时间:2023-10-30 00:05:17 24 4
gpt4 key购买 nike

我们正在为少数客户构建应用程序,每个客户都有自己的要求和相似的要求。我们还希望将所有代码保留在同一个应用程序中,而不是对其进行分支,并且 IF 不是一个好的选择,因为它会到处都是。

我计划为所有人提供基类。然后每个客户都有自己的类,覆盖方法将在其中执行特殊逻辑。

我们如何在编译时加载程序集而不是这样做

public class BaseClass {
public string getEventId()
}

public class ClassForJohn:BaseClass {
[override]
public string getEventId()
}

public class ClassForAdam:BaseClass {
[override]
public string getEventId()
}

void UglyBranchingLogicSomewhere() {
BaseClass eventOject;
if("John"==ConfigurationManager.AppSettings["CustomerName"]){
eventOject = new ClassForJohn();


}else if("Adam"==ConfigurationManager.AppSettings["CustomerName"]){
eventOject = new ClassForAdam();


}else{
eventOject = new BaseClass ();

}
eventId = eventOject.getEventId();
}

最佳答案

这就是我将插件(加载项)加载到我的一个项目中的方式:

const string PluginTypeName = "MyCompany.MyProject.Contracts.IMyPlugin";

/// <summary>Loads all plugins from a DLL file.</summary>
/// <param name="fileName">The filename of a DLL, e.g. "C:\Prog\MyApp\MyPlugIn.dll"</param>
/// <returns>A list of plugin objects.</returns>
/// <remarks>One DLL can contain several types which implement `IMyPlugin`.</remarks>
public List<IMyPlugin> LoadPluginsFromFile(string fileName)
{
Assembly asm;
IMyPlugin plugin;
List<IMyPlugin> plugins;
Type tInterface;

plugins = new List<IMyPlugin>();
asm = Assembly.LoadFrom(fileName);
foreach (Type t in asm.GetExportedTypes()) {
tInterface = t.GetInterface(PluginTypeName);
if (tInterface != null && (t.Attributes & TypeAttributes.Abstract) !=
TypeAttributes.Abstract) {

plugin = (IMyPlugin)Activator.CreateInstance(t);
plugins.Add(plugin);
}
}
return plugins;
}

我假设每个插件都实现了IMyPlugin。您可以以任何方式定义此接口(interface)。如果循环遍历插件文件夹中包含的所有 DLL 并调用此方法,则可以自动加载所有可用的插件。

通常您至少有三个程序集:一个包含接口(interface)定义、引用此接口(interface)程序集的主程序集和至少一个实现(当然也引用)此接口(interface)的程序集。

关于c# - 从不同的程序集动态加载类(具有自定义行为)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15142917/

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