【发布时间】:2013-03-09 14:20:43
【问题描述】:
project1 有class1 和interface1。 Class1 实现了 interface1。我有另一个项目将使用 interface1 测试这个 class1 方法。现在要注意的是我必须动态加载 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-equivalents 用于值-types) 为他们? -
我知道自定义参数类型是什么。但我无法将它们的引用添加到我的项目中,我必须通过动态加载它们来获取它们。
-
您可以使用Type.GetConstructors 并遍历所有可用的构造函数,直到获得所需的构造函数。编辑:找到它后,您可以调用它来创建一个完全绕过
Activator.CreateInstance方法的实例。 -
好的,一旦我在再次调用构造函数时获得了构造函数,我需要传递自定义参数对吗?
-
如果你已经有这些类型的实例,把它们传入。如果你没有,但你知道它们都是引用类型,你可以传入空值。否则,您可以通过
ConstructorInfo.GetParameters()并且对于每个ParameterInfo,您可以根据需要利用其ParameterType创建默认值(或调用其他构造函数)。
标签: c# reflection