C# 7:How can I deconstruct an object into a single value using a tuple?

后端 未结 2 1987
Happy的楠姐
Happy的楠姐 2021-01-12 02:52

One of the nice new features of C# 7 is the possibility to define deconstructors for classes and assign the deconstructed values directly to a value tuple.

However,

2条回答
  •  不思量自难忘°
    2021-01-12 03:34

    Although there is a type for tuples with a single element (ValueTuple), the shorthand syntax using parentheses doesn't work here.

    That's correct. The tuple syntax only works for tuples of 2 values or more, so the Deconstruct method with only one out parameter is not very useful. (There is even a ValueTuple type for 0 elements)

    The shortest solution is to just ignore the 2nd parameter:

    var (s1, _) = testObject;
    

    Edit: based on comments, a little clarification.
    As of C# 7, _ is no longer a variable in this situation. It is a new feature called 'discard'.
    Even if you have multiple out parameters (and even if they are different types) you can ignore any of them with an underscore:

    var (s1, _, _, _) = testObject;
    

提交回复
热议问题