繁体   English   中英

.Net 中的 Arrays.asList( ... )

[英]Arrays.asList( ... ) in .Net

我正在寻找编写以下 Java 代码的最简单方法

Arrays.asList(1L);

在.Net

谢谢

int[] a = new int[] { 1, 2, 3, 4, 5 };
List<int> list = a.ToList(); // Requires LINQ extension method

//Another way...
List<int> listNew = new List<int>(new []{ 1, 2, 3 }); // Does not require LINQ

请注意, LINQ.NET 3.5或更高版本中可用。

更多信息

由于数组已经在 .NET 中实现了IList<T> ,因此实际上不需要等效的Arrays.asList 只需直接使用数组,或者如果您觉得需要明确说明它:

IList<int> yourList = (IList<int>)existingIntArray;
IList<int> anotherList = new[] { 1, 2, 3, 4, 5 };

这与您将获得的 Java 原始版本非常接近:固定大小,并且写入传递到底层数组(尽管在这种情况下,列表和数组是完全相同的对象)。

除了对Devendra's answer的评论之外,如果你真的想在 .NET 中使用完全相同的语法,那么它看起来会像这样(尽管在我看来这是一个非常毫无意义的练习)。

IList<int> yourList = Arrays.AsList(existingIntArray);
IList<int> anotherList = Arrays.AsList(1, 2, 3, 4, 5);

// ...

public static class Arrays
{
    public static IList<T> AsList<T>(params T[] source)
    {
        return source;
    }
}

不确定您是要按照 Devendra 的回答将数组转换为列表,还是一次性创建一个新的填充列表(如果是第二个),则可以这样做:

new List<int>(){1, 2, 3, 4, 5};

事实上,填充集合的大括号语法将填充数组、字典等......

该静态方法的实现如下所示。

public static <T> List<T> asList(T... a) {
return new ArrayList<T>(a);
}

You 的等价物是使用 C# 中的 asList 方法编写相同的实用程序类,或者使用 Massif 提供的解决方案。

public static class Arrays {
      public static List<T> asList<T>(params T[] a)
        {
            return new List<T>(a);

        }
}

要创建单项数组,您只需执行以下操作:

long[] arr = new[] { 1L };
return new List<int> {A,B};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM