为何不能转换:
1:Assembly ass= Assembly.LoadFile(@"D:\dll\MytestClass.dll");
2:In st = (In)ass.CreateInstance("MytestClass.Student");In 是一个接口,“MytestClass”是一个命名空间。“Student” 是 “MytestClass”下的一个类。“Student”实现了“In” 接口。
现在的问题是:
程序的第一句能加载“MytestClass.dll”程序集ass, ass 通过调用CreateInstance方法也能创建出"MytestClass.Student" 的实例。但是就是无法执行程序的第二句。抛出了类转换异常。也就是无法从Object 向接口类型转换。也曾尝试这样转换:
MytestClass.Student stu=(MytestClass.Student)ass.CreateInstance("MytestClass.Student");
结果仍然无法转换。抛出类无法转换的异常。
无法理解无法转换的原因。十分感谢各位高手帮助小弟。不胜感激!!!
1:Assembly ass= Assembly.LoadFile(@"D:\dll\MytestClass.dll");
2:In st = (In)ass.CreateInstance("MytestClass.Student");In 是一个接口,“MytestClass”是一个命名空间。“Student” 是 “MytestClass”下的一个类。“Student”实现了“In” 接口。
现在的问题是:
程序的第一句能加载“MytestClass.dll”程序集ass, ass 通过调用CreateInstance方法也能创建出"MytestClass.Student" 的实例。但是就是无法执行程序的第二句。抛出了类转换异常。也就是无法从Object 向接口类型转换。也曾尝试这样转换:
MytestClass.Student stu=(MytestClass.Student)ass.CreateInstance("MytestClass.Student");
结果仍然无法转换。抛出类无法转换的异常。
无法理解无法转换的原因。十分感谢各位高手帮助小弟。不胜感激!!!
using System.Reflection;
using System.Runtime.CompilerServices;
private void button3_Click(object sender, EventArgs e)
{
Assembly ass = Assembly.LoadFile(@"H:\ClassEnty.dll");
InterfaceIns st = (InterfaceIns)ass.CreateInstance("ClassEnty.Student");
string ss = st.getname();
}ClassEntyusing System;
using System.Collections.Generic;
using System.Text;
using InterfaceIn;
namespace ClassEnty
{
public class Student : InterfaceIns
{
public string getname()
{
return "jack";
}
}}
InterfaceInusing System;
using System.Collections.Generic;
using System.Text;namespace InterfaceIn
{
public interface InterfaceIns
{
string getname();
}
}
public interface In{
String sayHi();
}
public Student:In{
public Student(){}//构造方法
public String sayHi(){//实现接口
return "hello"
}
}
}
public interface In{
String sayHi();
}
public Student:In{
public Student(){}//构造方法
public String sayHi(){//实现接口
return "hello"
}
}
}
===========
定义在同一个程序集中?
不同dll文件中同命名空间,同类名的类,其GUID可能不同,应次通过反射方式创建时可能会出问题
一个是程序debug目录下的,连外一个是D盘的
每次按F5 时,Debug下的dll多是全新地, 而D盘的确不是