C# 7:如何使用元组将对象解构为单个值?

C# 7:How can I deconstruct an object into a single value using a tuple?(C# 7:如何使用元组将对象解构为单个值?)

本文介绍了C# 7:如何使用元组将对象解构为单个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C# 7 的一个不错的新特性是可以为类定义解构器并将解构后的值直接分配给值元组.

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.

但是,在对象被解构为单个值的情况下,我找不到将其分配给元组的方法.尽管有一种用于具有单个元素的元组类型 (ValueTuple<T>),但使用括号的速记语法在这里不起作用.我发现访问解构器的唯一方法是直接调用 Deconstruct 方法,但这消除了它的好处,因为我可以为此使用任何方法.

However, in the case that the object is deconstructed into a single value, I can't find a way to assign it to a tuple. Although there is a type for tuples with a single element (ValueTuple<T>), the shorthand syntax using parentheses doesn't work here. The only way I found to access the deconstructor was to call the Deconstruct method directly, but this eliminates its benefit, as I could use any method for this end.

有人知道将对象解构为单个值的更好方法吗?

Does anyone know a better way to deconstruct an object into a single value?

这是我的测试代码:

class TestClass
{
    private string s;
    private int n;
    public TestClass(string s, int n) => (this.s, this.n) = (s, n);
    public void Deconstruct(out string s) => s = this.s;
    public void Deconstruct(out string s, out int n) => (s, n) = (this.s, this.n);
}

static void Main(string[] args)
{
    var testObject = new TestClass("abc", 3);

    var (s1) = testObject; // sytax error (comma expected)
    ValueTuple<string> t = testObject; // error: "no implicit conversion from TestClass to (string)"
    testObject.Deconstruct(out string s2); // this works
    var (s3, n) = testObject; // no problem

    Console.WriteLine($"{s1} {t.Item1} {s2} {s3} {n}");
    Console.ReadKey();
}

推荐答案

虽然有一种用于具有单个元素的元组的类型 (ValueTuple<T>),但使用括号的速记语法在这里不起作用.

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

没错.元组语法仅适用于 2 个或更多值的元组,因此只有一个 out 参数的 Deconstruct 方法不是很有用.(甚至还有 0 个元素的 ValueTuple 类型)

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;

根据评论,稍作澄清.
从 C# 7 开始,_ 在这种情况下不再是变量.这是一项名为丢弃"的新功能.
即使您有多个输出参数(即使它们是不同的类型),您也可以使用下划线忽略其中的任何一个:

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;

这篇关于C# 7:如何使用元组将对象解构为单个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C# 7:如何使用元组将对象解构为单个值?