【问题标题】:Casting new tuple to old one gives compilation error将新元组转换为旧元组会产生编译错误
【发布时间】:2017-09-20 11:24:55
【问题描述】:

使用下面的代码,

class Program
{
    static void Main(string[] args)
    {
        Tuple<int, int> test = TupleTest();

    }

    static (int, int) TupleTest()
    {
        return (1, 2);
    }

我收到以下编译时错误。

错误 CS0029 无法将类型 '(int, int)' 隐式转换为 'System.Tuple '

是否意味着新版本的 Tuple 与旧版本隐式不兼容?还是我在这里做错了什么?

【问题讨论】:

  • “新元组”是一种不同的类型,称为System.ValueTuple(有关差异的讨论,请参见this question),AFAIK 没有计划将其隐式转换为System.Tuple跨度>
  • 正如 Matej 在下面回答的那样,您应该使用扩展方法 (ToTuple)。这些不能作为用户定义的转换实现的原因是我们需要它们超过 arity 7。

标签: c# tuples c#-7.0


【解决方案1】:

是的,你应该使用扩展方法ToTuple。所以在你的例子中......

class Program
{
    static void Main(string[] args)
    {
        Tuple<int, int> test = TupleTest().ToTuple();

    }

    static (int, int) TupleTest()
    {
        return (1, 2);
    }

【讨论】:

    【解决方案2】:
    • 改用ValueTuple

    ValueTuple 测试 = TupleTest();

    • 使用ToTuple扩展方法(ToValueTuple也可用):

    元组测试 = TupleTest().ToTuple();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-17
      • 1970-01-01
      • 2014-10-06
      • 1970-01-01
      • 2021-11-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多