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

C#中(0,0) is (int x, int y) p语句里的p作用是什么?

问题:在C#语句(0, 0) is (int x, int y) p中,p的作用是什么?

场景A

此处x和y会被绑定为值均为0的标量变量,代码示例:

if ((0, 0) is (int x, int y))
{
    Console.WriteLine($"{x + y}");
}

if ((object)(0, 0) is (int x, int y))
{
    Console.WriteLine($"{x + y}");
}

场景B

可编译的情况

以下代码可以正常编译,这里的p是匹配成功后被赋值为原始元组实例的变量:

  • x、y是从元组中解构出来的标量变量,分别对应元组的两个元素;
  • p的类型是原始的ValueTuple<int, int>,自带Item1和Item2字段(并非以x、y作为命名字段)。

代码示例:

if ((0, 0) is (int x, int y) p)
{
    Console.WriteLine($"{x + y} and {p.Item1 + p.Item2}");
}

无法编译的情况

当把元组装箱为object后,添加p的代码无法编译:

if ((object)(0, 0) is (int x, int y) p)
{
    Console.WriteLine($"{x + y} and {p.Item1 + p.Item2}");
}  

编译错误提示:无法将类型“(int, int)”转换为“(int x, int y)”


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 18:01:19