任何大小的C#ValueTuple [英] C# ValueTuple of any size

查看:65
本文介绍了任何大小的C#ValueTuple的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以编写一个C#方法来接受具有任意数量的相同类型的项的值元组并将其转换为列表?

Is it possible to write a C# method that accepts a value tuple with any number of items of the same type and converts them into a list?

编辑2/6/2019
我接受了提供的答案作为正确答案。我还想提供一个使用不是接口的基类的解决方案,因为我正在尝试编写一个转换操作符,并且不允许从接口进行用户定义的转换。

Edit 2/6/2019 I accepted the Provided answer as the correct one. I wanted to also provide a solution that uses a base class that is not an interface, becuase I am trying to write a conversion operator and user defined conversions from an interface are not allowed.

public static class TupleExtensions
{
    public static IEnumerable<object> Enumerate(this ValueType tpl)
    {
        var ivt = tpl as ITuple;
        if (ivt == null) yield break;

        for (int i = 0; i < ivt.Length; i++)
        {
            yield return ivt[i];
        }
    }
}


推荐答案

您可以使用ValueTuples实现 ITup 接口。

You can use the fact that ValueTuples implement the ITuple interface.

唯一的问题是元组元素可以是任意类型,因此列表必须接受任何类型的

The only issue is that tuple elements can be of arbitrary type, so the list must accept any kind of type.

public List<object> TupleToList(ITuple tuple)
{
  var result = new List<object>(tuple.Length);
  for (int i = 0; i < tuple.Length; i++)
  {
    result.Add(tuple[i]);
  }
  return result;
}

这也可以作为扩展方法:

This also works as an extension method:

public static class ValueTupleExtensions
{
  public static List<object> ToList(this ITuple tuple)
  {
    var result = new List<object>(tuple.Length);
    for (int i = 0; i < tuple.Length; i++)
    {
      result.Add(tuple[i]);
    }
    return result;
  }
}

这样可以写 var list =(123, Text)。ToList();

编辑2020-06-18: 如果元组的每个元素都具有相同的类型,则可以使用正确的元素类型创建列表:

Edit 2020-06-18: If every element of the tuple is of the same type it's possible to create list with the proper element type:

public List<T> TupleToList<T>(ITuple tuple)
{
  var result = new List<T>(tuple.Length);
  for (int i = 0; i < tuple.Length; i++)
  {
    result.Add((T)tuple[i]);
  }
  return result;
}

这篇关于任何大小的C#ValueTuple的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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