2011-03-18 48 views
0

我需要一個NET 3.5類或多或少等價於C++ std::vector哪個.net 3.5集合用於一種類型的變長對象數組?

  • 包含的對象類型是由索引固定
  • 隨機存取
  • 可以創建一個空容器中,並根據需要
  • 添加對象

前面我用ArrayList,這是完全正確的,除了它存儲object,我要投檢索到的對象爲正確的類型,我可以補充一點東西那裏,本作編譯時類型檢查更難。

有什麼像ArrayList,但通過包含類型參數化?

回答

5

聽起來你List<T>後。例如,創建一個整數列表:

List<int> integers = new List<int>(); 
integers.Add(5); // No boxing required 
int firstValue = integers[0]; // Random access 

// Iteration 
foreach (int value in integers) 
{ 
    Console.WriteLine(value); 
} 

注意,你可能希望通過IEnumerable<T>ICollection<T>IList<T>而不是通過具體類型,揭露名單。

你不需要.NET 3.5,它們是在.NET 2中引入的(當泛型被引入作爲一個特性時)。然而,在.NET 3.5中,有LINQ可以使任何類型的序列更容易工作:

IEnumerable<int> evenIntegers = integers.Where(x => x % 2 == 0); 

(以及更多)。

4

List<T>

替換T與你喜歡的類型。

// Create an empty List<int> 
List<int> numbers = new List<int>(); 
numbers.Add(4); 

// Use the c# collection initializer to add some default values; 
List<int> numbersWithInitializer = new List<int> { 1, 4, 3, 4 }; 
相關問題