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

如何将C# switch模式匹配逻辑转为可迭代的模式函数列表?

替代Switch模式匹配的列表迭代方案

C#中确实无法直接将模式匹配的模式存储为变量,但可以通过封装匹配逻辑与处理逻辑的配对来实现类似列表迭代的效果,替代switch语句。下面是具体实现:

1. 定义输入类型(示例)

假设你的输入类型如下:

public class InputModel
{
    public string Property1 { get; set; }
    public int Property2 { get; set; }
}

2. 封装匹配与处理逻辑

将每个case的匹配条件转为Func<InputModel, bool>,处理逻辑转为Action<InputModel>,然后把它们组成配对列表:

var handlers = new List<(Func<InputModel, bool> Match, Action<InputModel> Handle)>
{
    // 对应原switch的第一个case
    (
        input => input.Property1 == "abc",
        input => 
        {
            // 这里写原case里的处理逻辑
        }
    ),
    // 对应原switch的第二个case
    (
        input => input.Property1 == "def" && new[] { 66, 67, 68, 80 }.Contains(input.Property2),
        input => 
        {
            // 这里写原case里的处理逻辑
        }
    )
};

3. 迭代执行匹配与处理

遍历列表,找到第一个匹配的项后执行处理逻辑,和switch的break逻辑一致:

foreach (var (match, handle) in handlers)
{
    if (match(input))
    {
        handle(input);
        break;
    }
}

扩展:复杂模式的适配

如果需要处理更复杂的模式(比如类型模式、嵌套属性模式),可以直接在Func中使用模式匹配表达式:

// 示例:匹配类型+嵌套属性的情况
input => input is UserModel { Profile: { Age: > 18 } }

可选:使用自定义类优化结构

如果配对列表需要复用或扩展,可以定义专门的处理类,让代码更清晰:

public class InputHandler
{
    public Func<InputModel, bool> MatchCondition { get; set; }
    public Action<InputModel> ProcessAction { get; set; }
}

// 初始化列表
var handlers = new List<InputHandler>
{
    new InputHandler
    {
        MatchCondition = input => input.Property1 == "abc",
        ProcessAction = input => { /* 处理逻辑 */ }
    }
};

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 21:25:56