List<T> Конструкторы
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Инициализирует новый экземпляр класса List<T>.
Перегрузки
| Имя | Описание |
|---|---|
| List<T>() |
Инициализирует новый экземпляр List<T> класса, который пуст и имеет начальную емкость по умолчанию. |
| List<T>(IEnumerable<T>) |
Инициализирует новый экземпляр класса, который содержит элементы, скопированные из указанной List<T> коллекции, и имеет достаточную емкость для размещения количества скопированных элементов. |
| List<T>(Int32) |
Инициализирует новый экземпляр класса, пустого List<T> и имеющего указанную начальную емкость. |
List<T>()
- Исходный код:
- List.cs
- Исходный код:
- List.cs
- Исходный код:
- List.cs
- Исходный код:
- List.cs
- Исходный код:
- List.cs
Инициализирует новый экземпляр List<T> класса, который пуст и имеет начальную емкость по умолчанию.
public:
List();
public List();
Public Sub New ()
Примеры
В следующем примере показан конструктор без параметров универсального List<T> класса. Конструктор без параметров создает список с емкостью по умолчанию, как показано при отображении Capacity свойства.
В примере добавляются, вставка и удаление элементов, показывающая, как изменяется емкость по мере использования этих методов.
List<string> dinosaurs = new List<string>();
Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);
dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Compsognathus");
Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
Console.WriteLine(dinosaur);
}
Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);
Console.WriteLine("Count: {0}", dinosaurs.Count);
Console.WriteLine("\nContains(\"Deinonychus\"): {0}",
dinosaurs.Contains("Deinonychus"));
Console.WriteLine("\nInsert(2, \"Compsognathus\")");
dinosaurs.Insert(2, "Compsognathus");
Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
Console.WriteLine(dinosaur);
}
// Shows accessing the list using the Item property.
Console.WriteLine("\ndinosaurs[3]: {0}", dinosaurs[3]);
Console.WriteLine("\nRemove(\"Compsognathus\")");
dinosaurs.Remove("Compsognathus");
Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
Console.WriteLine(dinosaur);
}
dinosaurs.TrimExcess();
Console.WriteLine("\nTrimExcess()");
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
Console.WriteLine("Count: {0}", dinosaurs.Count);
dinosaurs.Clear();
Console.WriteLine("\nClear()");
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
Console.WriteLine("Count: {0}", dinosaurs.Count);
/* This code example produces the following output:
Capacity: 0
Tyrannosaurus
Amargasaurus
Mamenchisaurus
Deinonychus
Compsognathus
Capacity: 8
Count: 5
Contains("Deinonychus"): True
Insert(2, "Compsognathus")
Tyrannosaurus
Amargasaurus
Compsognathus
Mamenchisaurus
Deinonychus
Compsognathus
dinosaurs[3]: Mamenchisaurus
Remove("Compsognathus")
Tyrannosaurus
Amargasaurus
Mamenchisaurus
Deinonychus
Compsognathus
TrimExcess()
Capacity: 5
Count: 5
Clear()
Capacity: 5
Count: 0
*/
Imports System.Collections.Generic
Partial Public Class Program
Public Shared Sub ShowPlanets()
Dim planets As New List(Of String)
Console.WriteLine(vbLf & "Capacity: {0}", planets.Capacity)
planets.Add("Mercury")
planets.Add("Venus")
planets.Add("Earth")
planets.Add("Mars")
planets.Add("Jupiter")
Console.WriteLine()
For Each planet As String In planets
Console.WriteLine(planet)
Next
Console.WriteLine(vbLf & "Capacity: {0}", planets.Capacity)
Console.WriteLine("Count: {0}", planets.Count)
Console.WriteLine(vbLf & "Contains(""Mars""): {0}", _
planets.Contains("Mars"))
Console.WriteLine(vbLf & "Insert(2, ""Saturn"")")
planets.Insert(2, "Saturn")
Console.WriteLine()
For Each planet As String In planets
Console.WriteLine(planet)
Next
' Shows how to access the list using the Item property.
Console.WriteLine(vbLf & "planets(3): {0}", planets(3))
Console.WriteLine(vbLf & "Remove(""Jupiter"")")
planets.Remove("Jupiter")
Console.WriteLine()
For Each planet As String In planets
Console.WriteLine(planet)
Next
planets.TrimExcess()
Console.WriteLine(vbLf & "TrimExcess()")
Console.WriteLine("Capacity: {0}", planets.Capacity)
Console.WriteLine("Count: {0}", planets.Count)
planets.Clear()
Console.WriteLine(vbLf & "Clear()")
Console.WriteLine("Capacity: {0}", planets.Capacity)
Console.WriteLine("Count: {0}", planets.Count)
End Sub
End Class
' This code example produces the following output:
'
' Capacity: 0
'
' Mercury
' Venus
' Earth
' Mars
' Jupiter
'
' Capacity: 8
' Count: 5
'
' Contains("Mars"): True
'
' Insert(2, "Saturn")
'
' Mercury
' Venus
' Saturn
' Earth
' Mars
' Jupiter
'
' planets(3): Earth
'
' Remove("Jupiter")
'
' Mercury
' Venus
' Saturn
' Earth
' Mars
'
' TrimExcess()
' Capacity: 5
' Count: 5
'
' Clear()
' Capacity: 5
' Count: 0
Комментарии
Емкость List<T> — это количество элементов, которые могут храниться List<T> . Так как элементы добавляются в List<T>объект, емкость автоматически увеличивается при необходимости при перераспределении внутреннего массива.
Если размер коллекции можно оценить, используя List<T>(Int32) конструктор и указав начальную емкость, необходимо выполнить ряд операций изменения размера при добавлении элементов в него List<T>.
Емкость можно уменьшить путем вызова TrimExcess метода или явного задания Capacity свойства. Уменьшение емкости перераспреждает память и копирует все элементы в ней List<T>.
Этот конструктор является операцией O(1).
Применяется к
List<T>(IEnumerable<T>)
- Исходный код:
- List.cs
- Исходный код:
- List.cs
- Исходный код:
- List.cs
- Исходный код:
- List.cs
- Исходный код:
- List.cs
Инициализирует новый экземпляр класса, который содержит элементы, скопированные из указанной List<T> коллекции, и имеет достаточную емкость для размещения количества скопированных элементов.
public:
List(System::Collections::Generic::IEnumerable<T> ^ collection);
public List(System.Collections.Generic.IEnumerable<T> collection);
new System.Collections.Generic.List<'T> : seq<'T> -> System.Collections.Generic.List<'T>
Public Sub New (collection As IEnumerable(Of T))
Параметры
- collection
- IEnumerable<T>
Коллекция, элементы которой копируются в новый список.
Исключения
collection равно null.
Примеры
В следующем примере показано List<T> конструктор и различные методы List<T> класса, которые действуют на диапазонах. Массив строк создается и передается конструктору, заполняя список элементами массива. Затем Capacity отображается свойство, чтобы показать, что начальная емкость является именно тем, что требуется для хранения входных элементов.
using System;
using System.Collections.Generic;
string[] input = { "Apple",
"Banana",
"Orange" };
List<string> fruits = new List<string>(input);
Console.WriteLine("\nCapacity: {0}", fruits.Capacity);
Console.WriteLine();
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
Console.WriteLine("\nAddRange(fruits)");
fruits.AddRange(fruits);
Console.WriteLine();
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
Console.WriteLine("\nRemoveRange(2, 2)");
fruits.RemoveRange(2, 2);
Console.WriteLine();
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
input = new string[] { "Mango",
"Pineapple",
"Watermelon" };
Console.WriteLine("\nInsertRange(3, input)");
fruits.InsertRange(3, input);
Console.WriteLine();
foreach (string fruit in fruits)
{
Console.WriteLine(fruit);
}
Console.WriteLine("\noutput = fruits.GetRange(2, 3).ToArray()");
string[] output = fruits.GetRange(2, 3).ToArray();
Console.WriteLine();
foreach (string fruit in output)
{
Console.WriteLine(fruit);
}
/*
This code example produces the following output:
Capacity: 3
Apple
Banana
Orange
AddRange(fruits)
Apple
Banana
Orange
Apple
Banana
Orange
RemoveRange(2, 2)
Apple
Banana
Banana
Orange
InsertRange(3, input)
Apple
Banana
Banana
Mango
Pineapple
Watermelon
Orange
output = fruits.GetRange(2, 3).ToArray()
Banana
Mango
Pineapple
*/
Imports System.Collections.Generic
Partial Public Class Program
Public Shared Sub ShowFruits()
Dim input() As String = { "Apple", _
"Banana", _
"Orange" }
Dim fruits As New List(Of String)(input)
Console.WriteLine(vbLf & "Capacity: {0}", fruits.Capacity)
Console.WriteLine()
For Each fruit As String In fruits
Console.WriteLine(fruit)
Next
Console.WriteLine(vbLf & "AddRange(fruits)")
fruits.AddRange(fruits)
Console.WriteLine()
For Each fruit As String In fruits
Console.WriteLine(fruit)
Next
Console.WriteLine(vbLf & "RemoveRange(2, 2)")
fruits.RemoveRange(2, 2)
Console.WriteLine()
For Each fruit As String In fruits
Console.WriteLine(fruit)
Next
input = New String() { "Mango", _
"Pineapple", _
"Watermelon" }
Console.WriteLine(vbLf & "InsertRange(3, input)")
fruits.InsertRange(3, input)
Console.WriteLine()
For Each fruit As String In fruits
Console.WriteLine(fruit)
Next
Console.WriteLine(vbLf & "output = fruits.GetRange(2, 3).ToArray")
Dim output() As String = fruits.GetRange(2, 3).ToArray()
Console.WriteLine()
For Each fruit As String In output
Console.WriteLine(fruit)
Next
End Sub
End Class
' This code example produces the following output:
'
' Capacity: 3
'
' Apple
' Banana
' Orange
'
' AddRange(fruits)
'
' Apple
' Banana
' Orange
' Apple
' Banana
' Orange
'
' RemoveRange(2, 2)
'
' Apple
' Banana
' Banana
' Orange
'
' InsertRange(3, input)
'
' Apple
' Banana
' Banana
' Mango
' Pineapple
' Watermelon
' Orange
'
' output = fruits.GetRange(2, 3).ToArray
'
' Banana
' Mango
' Pineapple
Комментарии
Элементы копируются в том List<T> же порядке, что и перечислитель коллекции.
Этот конструктор является операцией O(n), где n — это количество элементов в collection.
См. также раздел
Применяется к
List<T>(Int32)
- Исходный код:
- List.cs
- Исходный код:
- List.cs
- Исходный код:
- List.cs
- Исходный код:
- List.cs
- Исходный код:
- List.cs
Инициализирует новый экземпляр класса, пустого List<T> и имеющего указанную начальную емкость.
public:
List(int capacity);
public List(int capacity);
new System.Collections.Generic.List<'T> : int -> System.Collections.Generic.List<'T>
Public Sub New (capacity As Integer)
Параметры
- capacity
- Int32
Количество элементов, которые новый список может изначально хранить.
Исключения
capacity меньше 0.
Примеры
В следующем примере показано List<T>(Int32) конструктор. List<T> Создается строка с емкостью 4, так как конечный размер списка, как известно, ровно 4. Список заполняется четырьмя строками, а копия только для чтения создается с помощью AsReadOnly метода.
using System;
using System.Collections.Generic;
public partial class Program
{
public static void Main()
{
List<string> animals = new List<string>(4);
Console.WriteLine("\nCapacity: {0}", animals.Capacity);
animals.Add("Cat");
animals.Add("Dog");
animals.Add("Squirrel");
animals.Add("Wolf");
Console.WriteLine();
foreach (string animal in animals)
{
Console.WriteLine(animal);
}
Console.WriteLine("\nIList<string> roAnimals = animals.AsReadOnly()");
IList<string> roAnimals = animals.AsReadOnly();
Console.WriteLine("\nElements in the read-only IList:");
foreach (string animal in roAnimals)
{
Console.WriteLine(animal);
}
Console.WriteLine("\nanimals[2] = \"Lion\"");
animals[2] = "Lion";
Console.WriteLine("\nElements in the read-only IList:");
foreach (string animal in roAnimals)
{
Console.WriteLine(animal);
}
}
}
/*
This code example produces the following output:
Capacity: 4
Cat
Dog
Squirrel
Wolf
IList<string> roAnimals = animals.AsReadOnly()
Elements in the read-only IList:
Cat
Dog
Squirrel
Wolf
animals[2] = "Lion"
Elements in the read-only IList:
Cat
Dog
Lion
Wolf
*/
Imports System.Collections.Generic
Partial Public Class Program
Public Shared Sub Main()
Dim animals As New List(Of String)(4)
Console.WriteLine(vbLf & "Capacity: {0}", animals.Capacity)
animals.Add("Cat")
animals.Add("Dog")
animals.Add("Squirrel")
animals.Add("Wolf")
Console.WriteLine()
For Each animal As String In animals
Console.WriteLine(animal)
Next
Console.WriteLine(vbLf & _
"Dim roAnimals As IList(Of String) = animals.AsReadOnly")
Dim roAnimals As IList(Of String) = animals.AsReadOnly
Console.WriteLine(vbLf & "Elements in the read-only IList:")
For Each animal As String In roAnimals
Console.WriteLine(animal)
Next
Console.WriteLine(vbLf & "animals(2) = ""Lion""")
animals(2) = "Lion"
Console.WriteLine(vbLf & "Elements in the read-only IList:")
For Each animal As String In roAnimals
Console.WriteLine(animal)
Next
End Sub
End Class
' This code example produces the following output:
'
' Capacity: 4
'
' Cat
' Dog
' Squirrel
' Wolf
'
' Dim roAnimals As IList(Of String) = animals.AsReadOnly
'
' Elements in the read-only IList:
' Cat
' Dog
' Squirrel
' Wolf
'
' animals(2) = "Lion"
'
' Elements in the read-only IList:
' Cat
' Dog
' Lion
' Wolf
Комментарии
Емкость List<T> — это количество элементов, которые могут храниться List<T> . Так как элементы добавляются в List<T>объект, емкость автоматически увеличивается при необходимости при перераспределении внутреннего массива.
Если размер коллекции можно оценить, указывая начальную емкость, необходимо выполнить ряд операций изменения размера при добавлении элементов в него List<T>.
Емкость можно уменьшить путем вызова TrimExcess метода или явного задания Capacity свойства. Уменьшение емкости перераспреждает память и копирует все элементы в ней List<T>.
Этот конструктор является операцией O(1).
Предостережение
Если capacity он поступает из пользовательского ввода, предпочитайте использовать конструктор без параметров и разрешать коллекции изменять размер в виде элементов. Если необходимо использовать указанное пользователем значение, либо заклоните его в разумный предел (например, ) или убедитесь, Math.Clamp(untrustedValue, 0, 20)что число элементов соответствует указанному значению.