写一个CS文件,代码如下:
using System;
namespace Me
{
public class Student
{
public Student()
{
}
public void Print()
{
Console.WriteLine("我是人");
}
}
}
用csc.exe转换为dll文件,在另一个项目中加载,代码如下:
static void Main(string[] args)
{
Console.WriteLine(Assembly.LoadFile("D:\\1.dll").CreateInstance("Me.Student").GetType().ToString()); //打印出类别为:Me.Student,无错。
((Me.Student)Assembly.LoadFile("D:\\1.dll").CreateInstance("Me.Student")).Print();//报错:无法将类型为“Me.Student”的对象强制转换为类型“Me.Student”。
}
以上错误,本人苦思几天不明其理,希望大家各自发表自己的看法,一起探讨这个问题。本人菜鸟,麻烦大家说仔细点。
using System;
namespace Me
{
public class Student
{
public Student()
{
}
public void Print()
{
Console.WriteLine("我是人");
}
}
}
用csc.exe转换为dll文件,在另一个项目中加载,代码如下:
static void Main(string[] args)
{
Console.WriteLine(Assembly.LoadFile("D:\\1.dll").CreateInstance("Me.Student").GetType().ToString()); //打印出类别为:Me.Student,无错。
((Me.Student)Assembly.LoadFile("D:\\1.dll").CreateInstance("Me.Student")).Print();//报错:无法将类型为“Me.Student”的对象强制转换为类型“Me.Student”。
}
以上错误,本人苦思几天不明其理,希望大家各自发表自己的看法,一起探讨这个问题。本人菜鸟,麻烦大家说仔细点。
解决方案 »
- 求助!
- Wave CDMA modem 收取中文短信乱码
- c# label.text中让每个字的颜色都不一样
- 撒分,谁能帮我填一行代码,ofcouse,请你们先编译运行清楚再告诉我答案,应该不难,就是本人初学泛型拐不过弯,书上这种例子一大片
- 小弟刚学.net,请问有谁有vs2005环境下的web 项目没有啊?能否给小弟一份,或给我网址,请问哪有下载啊?
- 这么添加新数据集可以么?
- c#.net应用程序中调用word“宏”的问题
- 怎样验证代理IP地址是否可以访问该网址?
- 请向C#能否向VFP一样开发单机版应用程序?
- 请问怎么擦除上次的绘制?没有vb里的xor,有别的办法吗?
- C# 取ACCESS字段
- 看F#适合做什么?
匪夷所思,怎么会想出 Type.GetProperty("Student")来呢?
2楼的,你知道为什么吗?今天问老师,他也没说清楚。
你可以把1.dll复制成为2.dll,然后就可以使用LoadFile分别装入它们,并且分别实例化。
public bool LoadPlugIn(string arg_strFileName, string arg_strInterface) {
Assembly pluginAssembly;
Type pluginType;
IQCPrjPlugin PluginInterface;
try {
pluginAssembly = Assembly.LoadFrom(arg_strFileName);
pluginType = pluginAssembly.GetType(arg_strInterface);
if (null == pluginType) {
MessageBox.Show("插件接口获取失败!\n" + " 插件:" + arg_strFileName + "\n" + " 接口:" + arg_strInterface,"错误:",MessageBoxButtons.OK,MessageBoxIcon.Error);
return false;
}
PluginInterface = (IQCPrjPlugin)Activator.CreateInstance(pluginType);
PluginInterface.init_plugin();
m_IPlugins.Add(PluginInterface);
}catch (Exception e) {
MessageBox.Show(e.Message);
MessageBox.Show(System.Environment.StackTrace);
return false;
}
return true;
}
如果你没有引用另一个dll(注意是另一个,而不是同一个),你的代码((Me.Student)Assembly.LoadFile("D:\\1.dll").CreateInstance("Me.Student")).
中的强制类型转换代码就不可能编译通过!能够强制类型转换,就说明你首先引用了一个dll,这个dll中的模块包含Me.Student定义。而你装入的d:\1.dll有99%的可能性并不是应用程序运行时(通常自动复制到)在bin\debug或者bing\release目录下的dll。这样就有两个不同来源的dll被装载进入应用程序域了。
正解... 必须保证 D:\\1.dll类Me.Student和你的Me.Student 是同一个程序集.....
也就是说 你的程序集必须引用这个dll才可以...
另外
方法1 如果不引用..那就做接口dll 两边都引用.到时候转换为接口
方法2 一路反射调用到底..
谢谢大家