我有两个文件夹,一个文件夹是文件,另一个文件夹是DLL文件,我不知道DLL文件目录中有哪些或多少个DLL(模块化使用)。 在每个 DLL 文件中都有一个获取 FileInfo 作为参数的函数。 我如何才能对文件目录中的每个文件运行 DLL 中的所有函数?
例如,其中一个DLL文件:
using System;
using System.IO;
namespace DLLTest
{
public class DLLTestClass
{
public bool DLLTestFunction(FileInfo file)
{
return file.Exists;
}
}
}
主要内容:
DirectoryInfo filesDir = new DirectoryInfo(path_to_files_Directory);
DirectoryInfo dllsDir = new DirectoryInfo(path_to_dlls_Directory);
foreach(FileInfo file in filesDir.getFiles())
{
//How do I run each one of the dll funtions on each one of the files?
}
非常感谢。
最佳答案
C# 是静态类型语言,因此如果您想从多个程序集中调用特定函数,第一步是为此类函数定义一个具有接口(interface)的项目。
您必须创建一个具有一个接口(interface)的项目(称为 ModuleInterface 或其他名称):
public interface IDllTest
{
bool DLLTestFunction(FileInfo file);
}
那么你所有的 Dll 项目必须至少有一个实现这个接口(interface)的类:
public class DLLTestClass : IDllTest
{
public bool DLLTestFunction(FileInfo file)
{
return file.Exists;
}
}
请注意上面IDllTest 的实现(您必须添加对项目ModuleInterface 的引用)。
最后,在您的主项目中,您必须从目录加载所有程序集:
DirectoryInfo dllsDir = new DirectoryInfo(path_to_dlls_Directory);
foreach(FileInfo file in dllsDir.getFiles())
{
//Load the assembly
Assembly assembly = Assembly.LoadFile (file.FullName);
//Get class which implements the interface IDllTest
Type modules = assembly.GetTypes ().SingleOrDefault(x => x.GetInterfaces().Contains(typeof(IDllTest)));
//Instanciate
IDllTest module = (IDllTest)Activator.CreateInstance (modules);
//Call DllTestFunction (you have to define anyFileInfo)
module.DLLTestFunction(anyFileInfo);
}
它可能需要一些调整,因为我没有测试它! 不过,我确信这是要遵循的步骤。
引用(法语):http://www.lab.csblo.fr/implementer-un-systeme-de-plugin-framework-net-c/
我希望我的英语是可以理解的,欢迎指正。
关于C#动态使用DLL函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41206202/