我的程序中需要动态加载另一个assembly(只知道它的绝对地址,如C:\XXX\YY\MyAssembly.dll),而且知道它里有一个含有MyAttribute属性的类(类的名字并不知道,只知道它有MyAttribute属性)。我在我的程序中改如何动态加载这个assembly,并且创建那个我所需要的类的一个实例?(就是那个有MyAttribute属性的类的一个实例)thanks
调试欢乐多
AppDomain app=System.AppDomain.CreateDomain("newapp");
object obj= app.CreateInstanceAndUnwrap(ass.GetName(), "类名");
可以通过遍历出类名后,然后通过上面的方法进行判断类的属性是否为你想要的,然后再获取类名。相应的操作其实例。
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);
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;