问题
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