我为了利用反射实现插件,做了一下的测试:1 新建一个类库工程,添加一个接口
namespace CLI
{
public interface IDog
{
void Show();
}
}
编译成功,生成CLI.dll
2 新建另一个类库工程 ,引用上面的CLI,添加了一个IDog的实例.
using CLI;
namespace BlackDog
{
public class BlackDog:IDog
{
public BlackDog(){}
public void Show()
{
Console.WriteLine("I am BlackDog!");
}
}
}
编译成功.
3 新建测试工程,TestAS
使用Assembly.Load(),加载BlackDog.dll
using System;
using System.Windows.Forms;
using System.Reflection;
using CLI;
namespace TestAS
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
class MainC
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main(string[] args)
{
try
{

string path="Application.StartupPath + \\BlackDog.dll";
if(System.IO.File.Exists(path))
                               Console.Write("BlackDog here\n"); Assembly ab=Assembly.Load(path);

Type[] types=ab.GetTypes();
Console.Write("Types in Blackdog.dll:\n");
foreach(Type t in types)
{
Console.WriteLine(t.Name );
}
Console.WriteLine("--------------");
}
catch(Exception ec)
{
Console.WriteLine(ec.Message);
}
Console.Read();
}
}
}
编译成功!!!
把blackdog.dll放到test的debug目录下,运行. 
显示 BlackDog here 说明,找到了Blackdog.dll,
但是load失败,说:找不到文件或依赖,
文件一定是有的了,
那就是找不到依赖了,为什么?他用的那个CLI.dll就在那个目录啊!!请高手指教!

解决方案 »

  1.   

    CLI.dll 和 Blackdog.dll 在同一目录下吗?你知道 Load 失败但是你知道是 Blackdog.dll 的加载失败还是  CLI.dll 的 Load 失败?而且读文件应该用 LoadFile 方法吧?
      

  2.   

    下面的代码调试通过:
    public static void Main(string[] args)
            {
                try
                {
                    string path=string.Format(@"{0}\BlackDog.dll", Application.StartupPath);
                    if(System.IO.File.Exists(path))
                        Console.Write("BlackDog here\n");                Assembly ab=Assembly.LoadFile(path);
                    Type[] types=ab.GetTypes();
                    Console.Write("Types in Blackdog.dll:\n");
                    foreach(Type t in types)
                    {
                        Console.WriteLine(t.Name );
                    }
                    Console.WriteLine("--------------");
                }
                catch(Exception ec)
                {
                    Console.WriteLine(ec.Message);
                }
                Console.Read();
            }