各位前辈好!
小弟有这么个问题,关于动态载入DLL的。
首先我有一个 interface.cs 中定义了一个 interface
namespace demo
{
public interface IElement
{
void Print();
}
}
编译:csc /t:library /out:interface.dll interface.cs
然后有个 list.cs 实现了上面的 interface
namespace demo
{
public class List : IElement
{
public void Print()
{
System.Console.WriteLine("list");
}
}
}
编译:csc /t:library /out:list.dll /r:interface.dll list.cs最后写了个测试程序:
using System;
using System.Reflection;namespace demo
{
public class Program
{
static void Main()
{
Assembly ass = Assembly.LoadFrom("list.dll");
Type t = ass.GetType("demo.List");
IElement o = (IElement)Activator.CreateInstance(t);
o.Print();
}
}
}
编译:csc /r:interface.dll /out:program.exe program.cs现在运行 program.exe,ok,没问题。
但是我现在想要这样编译:
csc /t:library /out:list.dll interface.cs list.cs
csc /out:program.exe interface.cs program.cs然后我运行 program.exe,出错:
未处理的异常:  System.InvalidCastException: 无法将类型为“demo.List”的对象强制
转换为类型“demo.IElement”。
请问这是为什么?怎么样才能达到我的需求啊?难道一定要用 /r:interface.dll 的方式吗,我是不想多出一个dll来。多不爽啊!

解决方案 »

  1.   

    搂主把下面这句:
    IElement o = (IElement)Activator.CreateInstance(t); 改成:
    IElement o = t.GetConstructor(new Type[] { }).Invoke(null) as IElement;看看呢?
      

  2.   

    /r:interface.dll   你不引用他,肯定报错了,所以你要用一个IDE,VS2005中编译什么麻烦都没了
      

  3.   

    不是这样的,不过结贴算了。应该是appdomain相关的问题