簡體   English   中英

C#在沒有構建時引用的情況下在運行時調用靜態方法?

[英]C# call a static method at runtime without a build time reference?

我正在用C#.net(2.0)編寫一個系統。 它具有可插拔模塊的架構。 可以將程序集添加到系統中,而無需重建基礎模塊。 為了建立與新模塊的連接,我希望嘗試按名稱在其他模塊中調用靜態方法。 我不希望在構建時以任何方式引用被調用的模塊。

回到我從.dll文件的路徑開始編寫非托管代碼時,我會使用LoadLibrary()將.dll放入內存,然后使用get GetProcAddress()獲取指向我希望調用的函數的指針。 如何在C#/ .NET中實現相同的結果。

使用Assembly.LoadFrom(...)加載程序集后,您可以按名稱獲取類型並獲取任何靜態方法:

Type t = Type.GetType(className);

// get the method
MethodInfo method = t.GetMethod("MyStaticMethod",BindingFlags.Public|BindingFlags.Static);

Then you call the method:

method.Invoke(null,null); // assuming it doesn't take parameters

這是一個樣本:

        string assmSpec = "";  // OS PathName to assembly name...
        if (!File.Exists(assmSpec))
            throw new DataImportException(string.Format(
                "Assembly [{0}] cannot be located.", assmSpec));
        // -------------------------------------------
        Assembly dA;
        try { dA = Assembly.LoadFrom(assmSpec); }
        catch(FileNotFoundException nfX)
        { throw new DataImportException(string.Format(
            "Assembly [{0}] cannot be located.", assmSpec), 
            nfX); }
        // -------------------------------------------
        // Now here you have to instantiate the class 
        // in the assembly by a string classname
        IImportData iImp = (IImportData)dA.CreateInstance
                          ([Some string value for class Name]);
        if (iImp == null)
            throw new DataImportException(
                string.Format("Unable to instantiate {0} from {1}",
                    dataImporter.ClassName, dataImporter.AssemblyName));
        // -------------------------------------------
       iImp.Process();  // Here you call method on interface that the class implements

暫無
暫無

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

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