簡體   English   中英

C#動態使用DLL函數

[英]C# use DLL functions dynamically

我有兩個文件夾,一個文件夾和文件,另一個文件夾有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項目必須至少有一個實現這個接口的classe:

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/

我希望我的英語是可以理解的,隨時糾正我。

Niels提出了一個非常好的解決方案,界面清晰。 如果您不想創建接口,或者您不能迭代所有類型和方法來查找已知簽名:

var definedTypes = Assembly.LoadFile("file").DefinedTypes;
foreach(var t in definedTypes)
{
    foreach(var m in t.GetMethods())
    {
        var parameters = m.GetParameters();
        if (parameters.Length ==1 && parameters[0].ParameterType == typeof(FileInfo))
        {
            var instanse = Activator.CreateInstance(t);
            m.Invoke(instanse, new[] { fileInfo });
         }
     }
}

為此你需要所有類都有一個無參數構造函數來實現它。 作為Invoke方法的參數,您可以提供fileInfo對象。

您必須加載程序集動態查找其中的函數並調用它。 這里描述所有步驟

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM