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

寻求基于类型从多列表中选择的更优雅C#实现方式

优化泛型类型匹配的列表获取方法

我有一段泛型方法代码,调用时会根据传入的实体类型返回对应的Guid列表。现在的实现需要创建T的实例来做switch匹配,这点我不太满意,但代码其他部分还算简洁易读。我见过另一种基于typeof(T)的switch写法,但觉得比我现在的方案更差。

参考的typeof写法示例

switch (typeof(T))
{
    case Type intType when intType == typeof(int):
        ...
    case Type decimalType when decimalType == typeof(decimal):
        ...
    default:
        ...
}

当前实现代码

public List<Guid> GetListForType<T>() where T : BaseEntity, new()
{
    //HACK: 找不到更优雅的实现方式
    return new T() switch
    {
        Education => EducationSelection,
        Language => LanguageSelection,
        Knowledge => KnowledgeSelection,
        Work => WorkSelection,
        Project => ProjectSelection,
        _ => throw new NotImplementedException()
    };
}

#region Lists

public List<Guid> EducationSelection { get; set; } = new();
//注:Language目前未使用
public List<Guid> LanguageSelection { get; set; } = new();
public List<Guid> KnowledgeSelection { get; set; } = new();
public List<Guid> WorkSelection { get; set; } = new();
public List<Guid> ProjectSelection { get; set; } = new();

#endregion

优化方案

方案1:类型-列表映射字典

通过提前构建字典存储类型与对应列表的关联,完全避免创建实例,同时提升扩展性:

private readonly Dictionary<Type, Func<List<Guid>>> _typeListMap;

// 在类的构造函数中初始化映射关系
public YourClass()
{
    _typeListMap = new Dictionary<Type, Func<List<Guid>>>
    {
        { typeof(Education), () => EducationSelection },
        { typeof(Language), () => LanguageSelection },
        { typeof(Knowledge), () => KnowledgeSelection },
        { typeof(Work), () => WorkSelection },
        { typeof(Project), () => ProjectSelection }
    };
}

public List<Guid> GetListForType<T>() where T : BaseEntity
{
    if (_typeListMap.TryGetValue(typeof(T), out var getList))
    {
        return getList();
    }
    throw new NotImplementedException();
}

优势:

  • 无需创建T的实例,可移除泛型约束中的new()(如果其他地方不需要的话)
  • 映射关系集中管理,新增类型只需在字典中添加一行,维护成本低
  • 逻辑直观,无“hack”代码

方案2:简化的typeof模式匹配

如果觉得字典方式过重,可优化typeof(T)的switch写法,避免冗余变量:

public List<Guid> GetListForType<T>() where T : BaseEntity
{
    return typeof(T) switch
    {
        _ when typeof(T) == typeof(Education) => EducationSelection,
        _ when typeof(T) == typeof(Language) => LanguageSelection,
        _ when typeof(T) == typeof(Knowledge) => KnowledgeSelection,
        _ when typeof(T) == typeof(Work) => WorkSelection,
        _ when typeof(T) == typeof(Project) => ProjectSelection,
        _ => throw new NotImplementedException()
    };
}

这个写法去掉了多余的类型变量声明,比参考的typeof写法更简洁,同时避免了创建实例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 06:27:36