我正在寻找编写以下Java代码的最简单方法
Arrays.asList(1L);
Run Code Online (Sandbox Code Playgroud)
在.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
Run Code Online (Sandbox Code Playgroud)
请注意,LINQ可用.NET 3.5或更高.
更多信息
由于数组已经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)