簡體   English   中英

使用C#Reflection調用方法時嵌入/引用另一個DLL程序集的方法

[英]Way to embed/reference another DLL assembly while invoking a method using C# Reflection

無論如何,有沒有使用帶有嵌入式/引用dll的C#Reflection調用方法的方法?

例如,考慮以下senario。 我有一個程序集調用User.dll ,其類如下

namespace User
{
    public class UserInfo
    {
        public static string Name = "Username";
    }
}

使用上面的dll作為參考,我可以編譯以下代碼並訪問UserInfo.Name變量。

using User;
using System.Windows.Forms;

public class Test
{
    public Test()
    {
        MessageBox.Show("Name : " + UserInfo.Name);
    }
}

考慮以上代碼在另一個名為Test.dll程序集的dll中。 當我嘗試調用構造函數時,使用Assembly.LoadFile(“ Test.dll”)和C#反射,獲取未找到File的運行時錯誤。

錯誤

System.Reflection.TargetInvocationException:調用的目標引發了異常。 ---> System.IO.FileNotFoundException:無法加載文件或程序集'DynamicAssembly,版本= 0.0.0.0,區域性=中性,PublicKeyToken =空'或其依賴項之一。 該系統找不到指定的文件。 在Test..ctor()處-內部異常堆棧跟蹤的結尾-在System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags System.Reflection.ConstructorInfo.Invoke(Object []參數)的invokeAttr,活頁夾活頁夾,Object []參數,CultureInfo文化)

Assembly.LoadFile方法僅加載指定的文件。 在這種情況下,您需要使用Assembly.LoadFrom方法。 請檢查Assembly.LoadFile和Assembly.LoadFrom之間的區別

LoadFrom()通過Fusion,可以重定向到其他路徑下的另一個程序集,但如果已經在LoadFrom上下文中加載了該程序集,則具有相同的標識。

LoadFile()根本不通過Fusion進行綁定-加載程序僅繼續進行並完全加載*調用者請求的內容。 它不使用Load或LoadFrom上下文。

您正在執行的代碼示例將像

    static void Main(string[] args)
    {
        var fileName = ""; //put here test.dll path
        Assembly ass = Assembly.LoadFrom(fileName);

        var type = ass.GetType("Test.Test"); 

        var test = Activator.CreateInstance(type);
    }

我有同樣的問題。

我只是將DLL復制到項目的bin文件夾中。

暫無
暫無

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

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