IDictionary.Item[Object] 属性
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
获取或设置具有指定键的元素。
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
要获取或设置的元素的键。
属性值
具有指定键的元素,或者 null 如果该键不存在。
例外
key 是 null。
示例
下面的代码示例演示如何实现属性 Item[] 。 该代码示例是 IDictionary 类中的一个较大示例的一部分。
public object this[object key]
{
get
{
// If this key is in the dictionary, return its value.
Int32 index;
if (TryGetIndexOfKey(key, out index))
{
// The key was found; return its value.
return items[index].Value;
}
else
{
// The key was not found; return null.
return null;
}
}
set
{
// If this key is in the dictionary, change its value.
Int32 index;
if (TryGetIndexOfKey(key, out index))
{
// The key was found; change its value.
items[index].Value = value;
}
else
{
// This key is not in the dictionary; add this key/value pair.
Add(key, value);
}
}
}
Public Property Item(ByVal key As Object) As Object Implements IDictionary.Item
Get
' If this key is in the dictionary, return its value.
Dim index As Integer
If TryGetIndexOfKey(key, index) Then
' The key was found return its value.
Return items(index).Value
Else
' The key was not found return null.
Return Nothing
End If
End Get
Set(ByVal value As Object)
' If this key is in the dictionary, change its value.
Dim index As Integer
If TryGetIndexOfKey(key, index) Then
' The key was found change its value.
items(index).Value = value
Else
' This key is not in the dictionary add this key/value pair.
Add(key, value)
End If
End Set
End Property
注解
此属性提供使用以下语法访问集合中的特定元素的功能: myCollection[key]
还可以通过设置字典中不存在的键的值(例如,Item[])来使用该myCollection["myNonexistentKey"] = myValue属性来添加新元素。 但是,如果指定的键已存在于字典中,则设置该 Item[] 属性将覆盖旧值。 相反,该方法 Add 不会修改现有元素。
实现在是否允许密钥时 null有所不同。
C# 语言使用此 this关键字来 定义索引器,而不是实现 Item[] 属性。 Visual Basic 实现 Item[] 为默认属性,该属性提供相同的索引功能。