You need to enable JavaScript to run this app. C#如何使用泛型简化将类A、B转换为Common类集合的重复代码
优惠活动
大模型
产品
解决方案
定价
更多

C#如何使用泛型简化将类A、B转换为Common类集合的重复代码

实现方案

完全可以通过泛型封装重复逻辑,以下是两种符合要求的实现,均不需要修改原有A、B、Common类,仅需新增自定义工具类:

方案1:泛型+委托(编译时安全,推荐)

该方案通过委托传递属性取值逻辑,所有校验都在编译期完成,无运行时风险,性能最优:

// 新增的自定义工具类
public static class CommonConverter
{
    public static List<Common> ConvertToCommonList<T>(IEnumerable<T> sourceCollection, string typeText, Func<T, int> idSelector, Func<T, string> nameSelector)
    {
        var result = new List<Common>();
        foreach (var item in sourceCollection)
        {
            result.Add(new Common
            {
                Id = idSelector(item),
                Name = nameSelector(item),
                Type = typeText
            });
        }
        return result;
    }
}

调用方式:

var result = new List<Common>();
result.AddRange(CommonConverter.ConvertToCommonList(A_collection, "This is A", a => a.Id, a => a.Name));
result.AddRange(CommonConverter.ConvertToCommonList(B_collection, "This is B", b => b.Id, b => b.Name));

方案2:泛型+dynamic(写法更简洁)

如果希望代码更贴近你预期的通用循环写法,可以用dynamic绕过编译时类型检查:

// 新增的自定义工具类
public static class CommonConverter
{
    public static List<Common> ConvertToCommonList<T>(IEnumerable<T> sourceCollection, string typeText)
    {
        var result = new List<Common>();
        foreach (dynamic item in sourceCollection)
        {
            result.Add(new Common
            {
                Id = item.Id,
                Name = item.Name,
                Type = typeText
            });
        }
        return result;
    }
}

调用方式:

var result = new List<Common>();
result.AddRange(CommonConverter.ConvertToCommonList(A_collection, "This is A"));
result.AddRange(CommonConverter.ConvertToCommonList(B_collection, "This is B"));

注意:该方案仅适合确认传入的泛型类型一定包含Id和Name属性的场景,否则会在运行时抛出异常。

内容的提问来源于stack exchange,提问作者Bye

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 06:06:04