C#反射:将动态加载程序集的方法返回值转换为指定类型对象列表
Runtime Loading of demo.dll and Conversion to Target Type List
Here's a step-by-step implementation to load your demo.dll at runtime, invoke the GetItems() method, and convert the result to a list of your specified target type:
First, let's assume your target type looks something like this (adjust based on your actual needs):
public class MyTargetData { public string FirstName { get; set; } }
Now, here's the complete code to handle the assembly loading, method invocation, and conversion:
using System; using System.Reflection; using System.Collections; using System.Collections.Generic; public class AssemblyLoader { public List<MyTargetData> LoadAndConvertItems(string dllPath) { // Step 1: Load the demo.dll assembly Assembly demoAssembly = Assembly.LoadFrom(dllPath); // Step 2: Get references to the Utility and Data types from the assembly Type utilityType = demoAssembly.GetType("demo.Utility"); Type dataType = demoAssembly.GetType("demo.Data"); if (utilityType == null || dataType == null) { throw new InvalidOperationException("Could not find required types in demo.dll"); } // Step 3: Create an instance of the Utility class object utilityInstance = Activator.CreateInstance(utilityType); // Step 4: Get and invoke the GetItems() method MethodInfo getItemsMethod = utilityType.GetMethod("GetItems"); object rawItemsList = getItemsMethod.Invoke(utilityInstance, null); // Step 5: Convert the raw list to your target type List<MyTargetData> convertedList = new List<MyTargetData>(); PropertyInfo firstNameProperty = dataType.GetProperty("FirstName"); // Iterate over the items (using IEnumerable since we can't cast directly to List<Data>) foreach (var rawItem in (IEnumerable)rawItemsList) { string firstNameValue = (string)firstNameProperty.GetValue(rawItem); convertedList.Add(new MyTargetData { FirstName = firstNameValue }); } return convertedList; } }
Key Explanations:
- Assembly Loading:
Assembly.LoadFrom()loads the DLL from the specified path. UseAssembly.LoadFile()if you need to load multiple versions of the same assembly side-by-side. - Type Retrieval: We fetch the
demo.Utilityanddemo.Datatypes using their full names (namespace + class name). - Instance Creation:
Activator.CreateInstance()creates an instance of theUtilityclass, which runs its constructor and populates the initialitemslist. - Method Invocation: We use reflection to get the
GetItems()method and invoke it on the instance, returning the raw list ofDataobjects. - Conversion: Since we don't have a compile-time reference to
demo.Data, we useIEnumerableto iterate over the list. We then use reflection to access theFirstNameproperty of each raw item and map it to our target type.
Notes:
- Add error handling (try/catch blocks) for cases like missing DLLs, missing types/methods, or property access issues.
- If your target type has more properties, extend the mapping logic to include those by retrieving additional
PropertyInfoobjects fromdemo.Data. - For more complex mappings, you could use libraries like AutoMapper (but ensure you configure it to work with reflection-loaded types if needed).
内容的提问来源于stack exchange,提问作者Vimesh Shah
相关产品推荐
相关产品推荐

