OrderedDictionary.Item[] Свойство
Определение
Возвращает или задает указанное значение.Gets or sets the specified value.
Перегрузки
Item[Int32] |
Возвращает или задает значение по указанному индексу.Gets or sets the value at the specified index. |
Item[Object] |
Возвращает или задает значение с указанным ключом.Gets or sets the value with the specified key. |
Item[Int32]
Возвращает или задает значение по указанному индексу.Gets or sets the value at the specified index.
public:
property System::Object ^ default[int] { System::Object ^ get(int index); void set(int index, System::Object ^ value); };
public object this[int index] { get; set; }
public object? this[int index] { get; set; }
member this.Item(int) : obj with get, set
Default Public Property Item(index As Integer) As Object
Параметры
- index
- Int32
Отсчитываемый от нуля индекс возвращаемого или задаваемого значения.The zero-based index of the value to get or set.
Значение свойства
Значение элемента с заданным индексом.The value of the item at the specified index.
Реализации
Исключения
Свойство задается, и коллекция OrderedDictionary доступна только для чтения.The property is being set and the OrderedDictionary collection is read-only.
Значение параметра index
меньше нуля.index
is less than zero.
-или--or-
Значение параметра index
больше или равно значению свойства Count.index
is equal to or greater than Count.
Комментарии
Это свойство позволяет получить доступ к определенному элементу в коллекции, используя следующий синтаксис: myCollection[index]
.This property allows you to access a specific element in the collection by using the following syntax: myCollection[index]
.
Язык C# использует ключевое слово this для определения индексаторов вместо реализации Item[] Свойства.The C# language uses the this keyword to define the indexers instead of implementing the Item[] property. Visual Basic реализует Item[] как свойство по умолчанию, предоставляющее те же функции индексирования.Visual Basic implements Item[] as a default property, which provides the same indexing functionality.
Применяется к
Item[Object]
Возвращает или задает значение с указанным ключом.Gets or sets the value with the specified key.
public:
property System::Object ^ default[System::Object ^] { System::Object ^ get(System::Object ^ key); void set(System::Object ^ key, System::Object ^ value); };
public object this[object key] { get; set; }
public object? this[object key] { get; set; }
member this.Item(obj) : obj with get, set
Default Public Property Item(key As Object) As Object
Параметры
- key
- Object
Ключ, значение которого требуется получить или задать.The key of the value to get or set.
Значение свойства
Значение, связанное с указанным ключом.The value associated with the specified key. Если указанный ключ не найден, при попытке его получения возвращается значение null
, а при попытке задания ключа создается новый элемент с использованием указанного ключа.If the specified key is not found, attempting to get it returns null
, and attempting to set it creates a new element using the specified key.
Реализации
Исключения
Свойство задается, и коллекция OrderedDictionary доступна только для чтения.The property is being set and the OrderedDictionary collection is read-only.
Примеры
В следующем примере кода показано изменение OrderedDictionary коллекции.The following code example demonstrates the modification of an OrderedDictionary collection. В этом примере Item[] свойство используется для изменения записи словаря с помощью ключа "testKey2"
.In this example, the Item[] property is used to modify the dictionary entry with the key "testKey2"
. Этот код является частью более крупного примера кода, который можно просмотреть по адресу OrderedDictionary .This code is part of a larger code example that can be viewed at OrderedDictionary.
// Modifying the OrderedDictionary
if (!myOrderedDictionary->IsReadOnly)
{
// Insert a new key to the beginning of the OrderedDictionary
myOrderedDictionary->Insert(0, "insertedKey1", "insertedValue1");
// Modify the value of the entry with the key "testKey2"
myOrderedDictionary["testKey2"] = "modifiedValue";
// Remove the last entry from the OrderedDictionary: "testKey3"
myOrderedDictionary->RemoveAt(myOrderedDictionary->Count - 1);
// Remove the "keyToDelete" entry, if it exists
if (myOrderedDictionary->Contains("keyToDelete"))
{
myOrderedDictionary->Remove("keyToDelete");
}
}
// Modifying the OrderedDictionary
if (!myOrderedDictionary.IsReadOnly)
{
// Insert a new key to the beginning of the OrderedDictionary
myOrderedDictionary.Insert(0, "insertedKey1", "insertedValue1");
// Modify the value of the entry with the key "testKey2"
myOrderedDictionary["testKey2"] = "modifiedValue";
// Remove the last entry from the OrderedDictionary: "testKey3"
myOrderedDictionary.RemoveAt(myOrderedDictionary.Count - 1);
// Remove the "keyToDelete" entry, if it exists
if (myOrderedDictionary.Contains("keyToDelete"))
{
myOrderedDictionary.Remove("keyToDelete");
}
}
' Modifying the OrderedDictionary
If Not myOrderedDictionary.IsReadOnly Then
' Insert a new key to the beginning of the OrderedDictionary
myOrderedDictionary.Insert(0, "insertedKey1", "insertedValue1")
' Modify the value of the entry with the key "testKey2"
myOrderedDictionary("testKey2") = "modifiedValue"
' Remove the last entry from the OrderedDictionary: "testKey3"
myOrderedDictionary.RemoveAt(myOrderedDictionary.Count - 1)
' Remove the "keyToDelete" entry, if it exists
If (myOrderedDictionary.Contains("keyToDelete")) Then
myOrderedDictionary.Remove("keyToDelete")
End If
End If
Комментарии
Это свойство позволяет получить доступ к определенному элементу в коллекции, используя следующий синтаксис: myCollection[key]
.This property allows you to access a specific element in the collection by using the following syntax: myCollection[key]
.
Можно также использовать Item[] свойство для добавления новых элементов, задав значение ключа, который не существует в OrderedDictionary коллекции (например, myCollection["myNonexistentKey"] = myValue
).You can also use the Item[] property to add new elements by setting the value of a key that does not exist in the OrderedDictionary collection (for example, myCollection["myNonexistentKey"] = myValue
). Однако если указанный ключ уже существует в OrderedDictionary , установка Item[] Свойства перезаписывает старое значение.However, if the specified key already exists in the OrderedDictionary, setting the Item[] property overwrites the old value. В отличие от этого, Add метод не изменяет существующие элементы.In contrast, the Add method does not modify existing elements.
Ключ не может быть null
, а значение может быть.A key cannot be null
, but a value can be. Для различения null
возвращается, так как указанный ключ не найден и null
возвращается, поскольку значение указанного ключа равно null
, используйте Contains метод, чтобы определить, существует ли ключ в OrderedDictionary .To distinguish between null
that is returned because the specified key is not found and null
that is returned because the value of the specified key is null
, use the Contains method to determine if the key exists in the OrderedDictionary.