2011-03-10 22 views
8

我要找寫Java代碼最簡單的方法Arrays.asList(...)在.net

Arrays.asList(1L); 
在.net

感謝

+0

由於.NET數組已經是固定大小的IList ',所以在.NET中不需要編寫此代碼。在你的問題中代碼的最接近的字面翻譯只是'new [] {1L};'。 – LukeH 2011-03-10 13:30:00

回答

5
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或更高版本。

更多信息

+0

(在System.Linq中 - 只是爲了完成答案) – Massif 2011-03-10 12:17:03

+0

你說得對,那是該方法的'namespace'。謝謝。 – 2011-03-10 12:20:17

+1

但這不等同。 Arrays.asList(T ...)這意味着你不必創建一個數組,然後從它創建列表。 – 2011-03-10 12:27:01

1

不知道你是否希望將數組轉換成列表按德文德拉的答案或創建一個新填充的列表一氣呵成如果是第二個,那麼這將做到這一點:

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

事實上,用於填充集合的大括號語法將填充數組,字典等......

-1

該靜態方法的實現如下所示。

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

爲你WOLD來寫與方法asList相同實用類在C#或使用由地塊提出的解決方案的等價物。

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

     } 
} 
+0

請注意'ArrayList'有** not **'java.util。 ArrayList'(可憐的命名,但這是它必須保持的方式[由於串行格式])。 – 2011-03-10 13:09:44

+0

你在哪裏發現我的例子類似java.util.ArrayList? – 2011-03-10 13:14:24

+0

有人可以解釋爲什麼-1投票? – 2011-03-10 13:17:44

0

要創建單個項目數組,你只需做到這一點:

long[] arr = new[] { 1L }; 
8

由於磁盤陣列已經實現.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; 
    } 
} 
相關問題