project1具有class1和interface1。 Class1实现了interface1。我有另一个项目将使用interface1测试这个class1方法。现在catch是我必须动态加载project1.dll并使用接口方法调用class1方法。为此,我使用反射来加载project1.dll。现在,我从接口中获取methodInfo,并在调用此方法之前,我应该创建一个将调用该方法的类的实例。要使用activator.createInstance创建类的实例,我需要知道构造函数参数。现在,这些构造函数参数是自定义类型。正如我前面所说,我必须动态加载dll。那么是否有一种方法可以从组装载入中获取类型?或者其他任何方法来实现上述想法?以下是我的代码。使用反射从装配负载中获取类型
Assembly assembly = Assembly.LoadFrom(@"D:\Project1.dll");
Type[] typeArray = assembly.GetTypes();
object obj;
//First create the instance of the class
foreach (Type type in typeArray)
{
if (type.Name == "Class1")
{
Type[] types = new Type[4];
//I am not able to get the below customParams from the loaded assembly.
//Is there a way to do this. Can this be done without adding reference?
types[0] = typeof(CustompParam1);
types[1] = typeof(CustompParam2);
types[2] = typeof(CustompParam3);
types[3] = typeof(CustompParam4);
obj = Activator.CreateInstance(types);
}
}
//use the instance of the class to invoke the method from the interface
foreach (Type type in typeArray)
{
if (type.Name == "Interface1")
{
MethodInfo[] mInfo = type.GetMethods();
foreach (MethodInfo mi in mInfo)
{
mi.Invoke(obj, null);
}
}
}
我假设你既不知道自定义参数类型,你的意图是使用默认值(对于引用类型为'null',对于值类型为'0'等价物)调用构造函数? – 2013-03-20 13:14:39
我知道自定义参数类型是什么。但是我不能将它们的引用添加到我的项目中,我必须通过动态加载它们来获取它们。 – Virus 2013-03-20 13:17:22
您可以使用[Type.GetConstructors](http://msdn.microsoft.com/en-us/library/e687hf0d.aspx)遍历所有可用的构造函数,直到获得所需的构造函数。编辑:一旦你找到它,你可以调用它来创建一个实例完全绕过'Activator.CreateInstance'方法。 – 2013-03-20 13:18:52