手动加载DLL后,如何创建List<T>并转换类实例与方法返回结果类型?
解决动态加载MVC DLL后处理List的问题
我来帮你搞定这个反射操作的问题,你已经成功加载了DLL并拿到了相关类型信息,接下来我们一步步处理方法返回的object,并操作其中的Example对象:
1. 先正确调用目标方法拿到返回值
首先你需要获取到TestingCallFromSeparateConsoleApp方法的MethodInfo,然后执行调用得到结果:
// 获取目标方法的MethodInfo var method = smsAppInstance.GetType().GetMethod("TestingCallFromSeparateConsoleApp", BindingFlags.Public | BindingFlags.Instance); // 调用方法,得到返回的object类型结果 object listResult = method.Invoke(smsAppInstance, null);
2. 遍历返回的List集合
因为返回的是List<Example>,它实现了非泛型的IEnumerable接口,所以我们可以先转成这个接口来遍历里面的每个Example对象:
// 转换为非泛型IEnumerable,方便遍历集合 IEnumerable exampleItems = listResult as IEnumerable; if (exampleItems != null) { foreach (object exampleObj in exampleItems) { // 处理单个Example对象 HandleExample(exampleObj, ExampleClass); } }
3. 读取或修改Example对象的属性
写一个辅助方法来处理单个Example实例,通过反射来操作它的属性:
private void HandleExample(object exampleObj, Type exampleType) { // 读取属性值 int id = (int)exampleType.GetProperty("Id").GetValue(exampleObj); string prop1 = (string)exampleType.GetProperty("Property1").GetValue(exampleObj); string prop2 = (string)exampleType.GetProperty("Property2").GetValue(exampleObj); Console.WriteLine($"找到Example对象:Id={id}, Property1={prop1}, Property2={prop2}"); // 如果需要修改属性 exampleType.GetProperty("Property1").SetValue(exampleObj, "更新后的内容"); }
4. (可选)手动创建Example实例
如果需要新建Example对象,用Activator.CreateInstance就能实现:
// 创建一个新的Example实例 object newExample = Activator.CreateInstance(ExampleClass); // 设置属性值 ExampleClass.GetProperty("Id").SetValue(newExample, 3); ExampleClass.GetProperty("Property1").SetValue(newExample, "第三个实例"); ExampleClass.GetProperty("Property2").SetValue(newExample, "第三个实例的属性");
重要提示
- 因为你不能直接引用这个MVC DLL,所以所有操作都必须通过反射API来完成,不能在代码里直接写
Example或者List<Example>类型。 - 利用非泛型接口(比如
IEnumerable)是处理泛型集合的关键,这样不用依赖具体的泛型参数类型。 - 如果需要频繁操作这些属性,建议缓存
PropertyInfo对象,避免每次都调用GetProperty带来的性能损耗。
内容的提问来源于stack exchange,提问作者Neill
相关产品推荐
相关产品推荐

