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

Rom*_*man 9 .net java

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

Arrays.asList(1L);
Run Code Online (Sandbox Code Playgroud)

在.Net

谢谢

Dev*_*van 8

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
Run Code Online (Sandbox Code Playgroud)

请注意,LINQ可用.NET 3.5或更高.

更多信息

  • @汤姆,@ Devendra:这整个问题 - 以及大多数答案 - 完全没有实际意义..NET中的数组类型实现了`IList <T>`接口,因此数组已经为您提供了Java中`Arrays.asList`提供的功能. (4认同)
  • @Devendra:因为Java 中的数组没有实现`List&lt;T&gt;`;这就是为什么需要 `Arrays.asList` 方法(在数组上提供一个 `List&lt;T&gt;` 包装器)。.NET 中的数组确实实现了`IList&lt;T&gt;`,这就是为什么在.NET 中*不需要*等价物的`Arrays.asList`。 (2认同)

Luk*_*keH 8

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

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

这与你将获得的Java原始文件一样接近:固定大小,并且写入传递给底层数组(尽管在这种情况下,列表和数组是完全相同的对象).

关于Devendra答案的评论,如果你真的想在.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;
    }
}
Run Code Online (Sandbox Code Playgroud)