使用反射从程序集加载获取类型

本文关键字:加载 获取 取类型 程序集 反射 | 更新日期: 2023-09-27 18:04:47

项目1有class1和接口1。Class1实现接口1。我有另一个项目将使用interface1测试这个class1方法。现在的问题是,我必须动态加载project1.dll,并使用接口方法调用class1方法。为此,我正在使用反射加载project1.dll。现在,我从接口获得methodInfo,在调用这个方法之前,我应该创建一个将调用该方法的类的实例。来创建类的实例。我需要知道构造函数参数。现在,这些构造函数参数是自定义类型。正如我之前所说,我必须动态加载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);
        }
    }
}

使用反射从程序集加载获取类型

可以像创建类实例一样获取构造函数参数的实例

通过类型名称查找它们,调用Activator。为参数类型创建实例,然后将它们放入Activator中。创建原始类的实例