我的程序中需要动态加载另一个assembly(只知道它的绝对地址,如C:\XXX\YY\MyAssembly.dll),而且知道它里有一个含有MyAttribute属性的类(类的名字并不知道,只知道它有MyAttribute属性)。我在我的程序中改如何动态加载这个assembly,并且创建那个我所需要的类的一个实例?(就是那个有MyAttribute属性的类的一个实例)thanks

解决方案 »

  1.   

    System.Reflection.Assembly ass=System.Reflection.Assembly.LoadFile(@"C:\XXX\YY\MyAssembly.dll")
    AppDomain app=System.AppDomain.CreateDomain("newapp");
    object obj= app.CreateInstanceAndUnwrap(ass.GetName(), "类名");
    可以通过遍历出类名后,然后通过上面的方法进行判断类的属性是否为你想要的,然后再获取类名。相应的操作其实例。
      

  2.   

    ass = Assembly.LoadFrom(@"G:\C#Test\MyTest\MyTest\bin\Release\MyTest.dll");
    ass = Assembly.Load("MyTest");type = ass.GetType("MyTest.ReflectTest");MethodInfo method = type.GetMethod("WriteString");
    obj = ass.CreateInstance("MyTest.ReflectTest");string s = (string)method.Invoke(obj, new string[] { "测试" });
    Console.WriteLine(s);
    System.Threading.Thread.Sleep(1000);
      

  3.   

    我不知道类名的,只知道这个类有MyAttribute属性,改怎么做?
      

  4.   


    Assembly assembly = Assembly.Load("xxxxxx");
    foreach (Type type in assembly.GetExportedTypes())
    {
        if (type.IsClass)
        {
             object[] attributes = type.GetCustomAttribute(typeof(MyAttribute), false);
             if (attributes != null && attributes.Length > 0)
             {
                  return Activator.CreateInstance(type);
             }
        }
    }
    return null;
      

  5.   

    创建了就行了,因为我知道它实现了一个特定的接口。thanks