ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

C#动态使用DLL函数

2019-10-26 12:06:37  阅读:212  来源: 互联网

标签:modularity file dll c


我有两个文件夹,一个包含文件的文件夹,另一个包含DLL文件的文件夹,我不知道DLL文件目录(模块化使用)中有哪个或多少个DLL.
每个DLL文件中都有一个将FileInfo作为参数的函数.
我如何在files目录中的每个文件上的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#是静态类型的语言,因此,如果要从许多程序集中调用特定函数,则第一步是使用该函数的接口定义一个项目.

您必须使用一个接口创建一个项目(称为ModuleInterface或其他任何项目):

public interface IDllTest
{
    bool DLLTestFunction(FileInfo file);
}

然后,您所有的Dll项目都必须至少具有一个实现此接口的类:

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/

我希望我的英语是可以理解的,请随时纠正我.

标签:modularity,file,dll,c
来源: https://codeday.me/bug/20191026/1936430.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有