有没有办法让元组列表解构为 List<T>
?
我在使用以下代码示例时遇到以下编译错误:
Cannot implicitly convert type 'System.Collections.Generic.List< Deconstruct.Test>' to 'System.Collections.Generic.List<(int, int)>'
using System;
using System.Collections.Generic;
namespace Deconstruct
{
class Test
{
public int A { get; set; } = 0;
public int B { get; set; } = 0;
public void Deconstruct(out int a, out int b)
{
a = this.A;
b = this.B;
}
}
class Program
{
static void Main(string[] args)
{
var test = new Test();
var (a, b) = test;
var testList = new List<Test>();
var tupleList = new List<(int, int)>();
tupleList = testList; // ERROR HERE....
}
}
}
最佳答案
您需要显式转换 testList
( List<Test>
) 到 tupleList
( List<(int, int)>
)
tupleList = testList.Select(t => (t.A, t.B)).ToList();
说明:
您使用的代码就好像 Deconstruct
让您转换一个实现 Deconstruct
的类到一个元组( ValueTuple
),但这不是 Deconstruct
剂量。
来自文档 Deconstructing tuples and other types :
Starting with C# 7.0, you can retrieve multiple elements from a tuple or retrieve multiple field, property, and computed values from an object in a single deconstruct operation. When you deconstruct a tuple, you assign its elements to individual variables. When you deconstruct an object, you assign selected values to individual variables.
解构将多个元素返回给单个变量,而不是元组 (ValueTuple
)。
正在尝试转换 List<Test>
到 List<(int, int)>
像这样:
var testList = new List<Test>();
var tupleList = new List<(int, int)>();
tupleList = testList;
无法工作,因为您无法转换 List<Test>
到 List<(int, int)>
.它将产生一个编译器错误:
Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.List<(int, int)>'
尝试转换每个 Test
元素到 (int, int)
像这样:
tupleList = testList.Cast<(int, int)>().ToList();
无法工作,因为您无法转换 Test
到 (int, int)
.它将产生一个运行时错误:
System.InvalidCastException: 'Specified cast is not valid.'
尝试转换单个 Test
元素到 (int, int)
像这样:
(int, int) tuple = test;
无法工作,因为您无法转换 Test
到 (int, int)
.它将产生一个编译器错误:
Cannot implicitly convert type 'Deconstruct.Test' to '(int, int)'
关于c# - 用 List<T> 解构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56723303/