C# 将新元组转换为旧元组会导致编译错误
使用下面的代码C# 将新元组转换为旧元组会导致编译错误,c#,tuples,c#-7.0,C#,Tuples,C# 7.0,使用下面的代码 class Program { static void Main(string[] args) { Tuple<int, int> test = TupleTest(); } static (int, int) TupleTest() { return (1, 2); } 类程序 { 静态void Main(字符串[]参数) { Tuple test=TupleTest(); } 静
class Program
{
static void Main(string[] args)
{
Tuple<int, int> test = TupleTest();
}
static (int, int) TupleTest()
{
return (1, 2);
}
类程序
{
静态void Main(字符串[]参数)
{
Tuple test=TupleTest();
}
静态(int,int)TupleTest()
{
返回(1,2);
}
我得到以下编译时错误
错误CS0029无法将类型“(int,int)”隐式转换为
'System.Tuple这是否意味着新版本的Tuple与旧版本不兼容?或者我在这里做错了什么?是的,您应该使用扩展方法。因此在您的示例中
class Program
{
static void Main(string[] args)
{
Tuple<int, int> test = TupleTest().ToTuple();
}
static (int, int) TupleTest()
{
return (1, 2);
}
类程序
{
静态void Main(字符串[]参数)
{
Tuple test=TupleTest().ToTuple();
}
静态(int,int)TupleTest()
{
返回(1,2);
}
- 改用
:ValueTuple
- 使用
扩展方法(ToTuple
也可用):ToValueTuple
Tuple test=TupleTest().ToTuple();这个“新的Tuple”是一个不同类型的调用(请参阅以了解差异的讨论),而且目前还没有计划将其隐式转换为
系统。Tuple
正如Matej在下面回答的那样,您应该使用扩展方法(ToTuple
)。这些不能实现为用户定义转换的原因是我们需要它们超过arity 7。