You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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. Use Assembly.LoadFile() if you need to load multiple versions of the same assembly side-by-side.
  • Type Retrieval: We fetch the demo.Utility and demo.Data types using their full names (namespace + class name).
  • Instance Creation: Activator.CreateInstance() creates an instance of the Utility class, which runs its constructor and populates the initial items list.
  • Method Invocation: We use reflection to get the GetItems() method and invoke it on the instance, returning the raw list of Data objects.
  • Conversion: Since we don't have a compile-time reference to demo.Data, we use IEnumerable to iterate over the list. We then use reflection to access the FirstName property 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 PropertyInfo objects from demo.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:20:00