C# 7 模式匹配元组 [英] C# 7 Pattern Match with a tuple
问题描述
是否可以像这样使用 c# 7 在 switch 语句中使用模式匹配的元组:
Is it possible to use tuples with pattern matching in switch statements using c# 7 like so:
switch (parameter)
{
case ((object, object)) tObj when tObj.Item1 == "ABC":
break;
}
我收到一个错误,指出 tObj 在当前上下文中不存在
.
I get an error that says tObj does not exist in the current context
.
我也试过这个:
switch (parameter)
{
case (object, object) tObj when tObj.Item1 == "ABC":
break;
}
这很好用:
switch (parameter)
{
case MachineModel model when model.Id == "123":
break;
}
推荐答案
记住 C#7 元组只是语法糖,所以 (object, object)
实际上只是 System.ValueTuple<对象,对象>
.
Remember that C#7 tuples are just syntactic sugar, so (object, object)
is really just System.ValueTuple<object, object>
.
我猜开发团队在元组的新语法中没有考虑到这种特殊情况,但您可以这样做:
I guess that the dev team didn't take this particular situation into account for the new syntax for tuples, but you can do this:
switch (parameter)
{
case System.ValueTuple<object, object> tObj when tObj.Item1 == "x":
break;
}
此外,由于var 模式"将匹配任何内容并尊重类型,因此上述内容可以简化为:
Also, since the "var pattern" will match anything and respect the type, the above can be simplified to:
switch (parameter)
{
case var tObj when tObj.Item1 == "x":
break;
}
这篇关于C# 7 模式匹配元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!