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

查看:59
本文介绍了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开始,在这种情况下, _ 不再是变量.这是一个称为丢弃"的新功能.
即使您有多个out参数(即使它们是不同的类型),也可以使用下划线忽略其中的任何一个:

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:如何使用元组将对象解构为单个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆