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

C#列表模式匹配中不同模式的差异及`[..]`等模式等价性的疑问

C#列表模式匹配中不同模式的差异及[..]等模式等价性的疑问

我最近在研究C#的列表模式匹配,一开始的逻辑都挺顺的:

  • 模式[]只会匹配空列表;
  • 模式[_]只会匹配恰好包含一个元素的列表,以此类推,[_,_]就匹配恰好两个元素的列表。

这些规则对我来说都很符合逻辑,但接下来遇到的情况就让我有点摸不着头脑了——看起来[..]、[_, ..]和[.., _]这三个模式居然是等价的?这和我直觉里的预期不太一样。

我写了一段测试代码验证,结果它连续打印了6次true:

Console.WriteLine(new int[]{1} is [..]);        
Console.WriteLine(new int[]{1} is [_, ..]);
Console.WriteLine(new int[]{1} is [.., _]);

Console.WriteLine(new int[]{1,2} is [..]);      
Console.WriteLine(new int[]{1,2} is [_, ..]);
Console.WriteLine(new int[]{1,2} is [.., _]);

备注:内容来源于stack exchange,提问作者codymanix

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 11:34:34