[英]Get type from assembly load using reflection
The project1 has class1 and interface1. project1具有class1和interface1。 Class1 implements the interface1. Class1实现interface1。 I have another project that will test this class1 methods using interface1. 我有另一个项目,它将使用interface1测试此类class1方法。 Now the catch is I have to load the project1.dll dynamically and use the interface methods to make calls to class1 methods. 现在的问题是我必须动态加载project1.dll并使用接口方法来调用class1方法。 To do this, I am loading the project1.dll using reflection. 为此,我正在使用反射加载project1.dll。 Now, I get the methodInfo from the interface and before invoking this method, I should create an instance of the class that I will invoke the method. 现在,我从接口获取methodInfo,并且在调用此方法之前,我应该创建将调用该方法的类的实例。 To create a instance of the class using activator.createInstance I need to know the constructor params. 要使用activator.createInstance创建类的实例,我需要知道构造函数的参数。 Now, these constructor params are of custom type. 现在,这些构造函数参数为自定义类型。 As I said earlier I have to load the dll's dynamically. 如前所述,我必须动态加载dll。 So is there a way to get the type from the assembly load? 那么有没有办法从组装负载中获得类型呢? Or any other approach to achieve the above idea? 或任何其他方法来实现上述想法? Below is my code. 下面是我的代码。
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);
}
}
}
You could get the instances for constructor parameters the same way you create your class instance 您可以像创建类实例一样获取构造函数参数的实例
Find them by type name, the call Activator.CreateInstance for parameter type, and then put them into Activator.CreateInstance of your original class. 通过类型名称查找它们,然后调用Activator.CreateInstance作为参数类型,然后将其放入原始类的Activator.CreateInstance中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.