[英]How can I embed a dll to the output assembly with codedom, and use it as reference using C#?
[英]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.