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

C# Consolidator策略调用优化:寻求高可维护性实现方案

更优的C#集合合并(ConsolidateToString)实现方案

针对你遇到的三种方案的缺陷,推荐**「特性标记+自动扫描排序的策略调度」方案**,可以同时兼顾扩展性与可维护性,核心是把策略的匹配规则、优先级从硬编码分支/列表中解耦出来。

方案核心思路

  1. 用特性标记策略的优先级与目标处理类型,明确规则而非依赖隐性顺序
  2. 标准化策略接口,每个策略独立封装对应集合的合并逻辑
  3. 启动时自动扫描所有策略实现,按优先级排序后统一调度
  4. 调度时通过策略自身的匹配逻辑找到对应实现,无需复杂分支

具体实现代码

1. 定义优先级标记特性

用来标注策略的优先级(数值越高优先级越高)和目标处理的集合类型:

[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public class ConsolidatorPriorityAttribute : Attribute
{
    public int Priority { get; }
    public Type TargetCollectionType { get; }

    public ConsolidatorPriorityAttribute(int priority, Type targetCollectionType)
    {
        Priority = priority;
        TargetCollectionType = targetCollectionType;
    }
}

2. 标准化策略接口

统一策略的匹配与执行逻辑:

public interface IConsolidator
{
    // 判断当前策略是否能处理传入的集合
    bool CanHandle(IEnumerable collection);
    // 执行合并逻辑
    string ConsolidateToString(IEnumerable collection);
}

3. 实现具体策略

每个策略独立封装对应集合的合并逻辑,通过特性标记优先级:

// 处理List<string>的策略,优先级10
[ConsolidatorPriority(10, typeof(List<string>))]
public class ListStringConsolidator : IConsolidator
{
    public bool CanHandle(IEnumerable collection)
    {
        return collection is List<string>;
    }

    public string ConsolidateToString(IEnumerable collection)
    {
        var list = (List<string>)collection;
        return string.Join(";", list);
    }
}

// 处理HashSet<int>的策略,优先级20(比List<string>更高)
[ConsolidatorPriority(20, typeof(HashSet<int>))]
public class HashSetIntConsolidator : IConsolidator
{
    public bool CanHandle(IEnumerable collection)
    {
        return collection is HashSet<int>;
    }

    public string ConsolidateToString(IEnumerable collection)
    {
        var set = (HashSet<int>)collection;
        return string.Join(",", set.OrderBy(x => x));
    }
}

4. 统一调度器

自动扫描所有策略、按优先级排序,提供统一的合并入口:

public class ConsolidationDispatcher
{
    private readonly List<IConsolidator> _sortedConsolidators;

    public ConsolidationDispatcher()
    {
        // 扫描程序集中所有实现IConsolidator的非抽象类
        var consolidatorTypes = AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(a => a.GetTypes())
            .Where(t => typeof(IConsolidator).IsAssignableFrom(t) && !t.IsInterface && !t.IsAbstract);

        // 实例化策略并按优先级降序排序
        _sortedConsolidators = consolidatorTypes
            .Select(t => Activator.CreateInstance(t) as IConsolidator)
            .Where(c => c != null)
            .OrderByDescending(c =>
            {
                var attr = c.GetType().GetCustomAttribute<ConsolidatorPriorityAttribute>();
                return attr?.Priority ?? 0;
            })
            .ToList();
    }

    public string Consolidate(IEnumerable collection)
    {
        // 遍历排序后的策略,找到第一个能处理的执行
        foreach (var consolidator in _sortedConsolidators)
        {
            if (consolidator.CanHandle(collection))
            {
                return consolidator.ConsolidateToString(collection);
            }
        }

        // 未知集合类型的默认处理逻辑
        return string.Join(",", collection.Cast<object>());
    }
}

方案优势

  • 扩展性:新增合并逻辑只需实现IConsolidator并添加特性标记,无需修改任何现有代码,完全符合开闭原则
  • 可维护性:每个策略的逻辑独立封装,测试只需针对单个策略类,没有复杂的分支或依赖关系
  • 优先级可控:通过特性的Priority字段明确设置优先级,避免了策略顺序依赖的隐性问题,规则清晰可见
  • 自动管理:启动时自动扫描策略,无需手动维护策略列表或工厂分支,减少人为错误

可选优化

  • 如果是大型项目,可使用依赖注入容器(如Microsoft DI、Autofac)替代Activator.CreateInstance来管理策略实例
  • 若需要更复杂的匹配条件,可扩展ConsolidatorPriorityAttribute或在CanHandle中添加自定义判断逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 20:24:50