C# 7 Pattern Match with a tuple

安稳与你 提交于 2019-12-21 07:41:41

问题


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;
}

I get an error that says tObj does not exist in the current context.

I have tried this as well:

switch (parameter)
{
   case (object, object) tObj when tObj.Item1 == "ABC":
        break;
}

This works fine:

switch (parameter)
{
   case MachineModel model when model.Id == "123":
        break;
}

回答1:


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;
}

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;
}


来源:https://stackoverflow.com/questions/44706498/c-sharp-7-pattern-match-with-a-tuple

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!