为何不能转换:
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.   

    我试过了 没有 你说的问题 我得都正常ss  出来就是 jackusing InterfaceIn;
    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();
        }
    }
      

  2.   

    namespace MytestClass{
    public interface In{
      String sayHi();
    }
    public Student:In{
      public Student(){}//构造方法
       public String sayHi(){//实现接口
         return "hello"
      } 
    }
    }
      

  3.   

    namespace MytestClass{ 
    public interface In{ 
      String sayHi(); 

    public Student:In{ 
      public Student(){}//构造方法 
      public String sayHi(){//实现接口 
        return "hello" 
      } 


    ===========
    定义在同一个程序集中?
      

  4.   

    分两个程序集定义..,
    不同dll文件中同命名空间,同类名的类,其GUID可能不同,应次通过反射方式创建时可能会出问题
      

  5.   

    “不同dll文件中同命名空间,同类名的类,其GUID可能不同” 这句话不大明白什么意思。请指点。
      

  6.   

    就是,你其实有两个dll
    一个是程序debug目录下的,连外一个是D盘的
    每次按F5 时,Debug下的dll多是全新地, 而D盘的确不是