请单击以进行评分并提供反馈
MSDN
MSDN Library
.NET 开发
先前版本
 Item 属性
全部折叠/全部展开 全部折叠
此页面仅适用于
Microsoft Visual Studio 2005/.NET Framework 2.0

同时提供下列产品的其他版本:
.NET Framework 类库
Dictionary.Item 属性

注意:此属性在 .NET Framework 2.0 版中是新增的。

获取或设置与指定的键相关联的值。

命名空间:System.Collections.Generic
程序集:mscorlib(在 mscorlib.dll 中)

Visual Basic(声明)
Public Default Property Item ( _
    key As TKey _
) As TValue
Visual Basic(用法)
Dim instance As Dictionary(Of TKey, TValue)
Dim key As TKey
Dim value As TValue

value = instance(key)

instance(key) = value
C#
public TValue this [
    TKey key
] { get; set; }
C++
public:
virtual property TValue default [TKey] {
    TValue get (TKey key) sealed;
    void set (TKey key, TValue value) sealed;
}
J#
/** @property */
public final TValue get_Item (TKey key)

/** @property */
public final void set_Item (TKey key, TValue value)
JScript
JScript 支持使用索引属性,但不支持进行新的声明。

参数

key

要获取或设置的值的键。

属性值

与指定的键相关联的值。如果找不到指定的键,get 操作便会引发 KeyNotFoundException,而 set 操作会创建一个具有指定键的新元素。
异常类型条件

ArgumentNullException

key 为 空引用(在 Visual Basic 中为 Nothing)。

KeyNotFoundException

已检索该属性,并且集合中不存在 key

此属性提供使用以下 C# 语法访问集合中特定元素的能力:myCollection[key](在 Visual Basic 中为 myCollection(key))。

通过设置 Dictionary 中不存在的键值(例如,myCollection["myNonexistentKey"] = myValue),还可以使用 Item 属性添加新元素。但是,如果指定的键已经存在于 Dictionary 中,则设置 Item 属性将改写旧值。相比之下,Add 方法不修改现有元素。

键不能为 空引用(在 Visual Basic 中为 Nothing),但是如果值类型 TValue 为引用类型,该值则可以为空。

获取或设置此属性的值的运算复杂度接近 O(1)。

下面的代码示例使用 Item 属性(在 C# 中为索引器)来检索值,演示当请求的键不存在时将引发 KeyNotFoundException,并演示与键相关联的值可被替换。

该示例还演示当程序必须经常尝试字典中不存在的键值时,如何使用 TryGetValue 方法作为一种更有效的方法来检索值。

此代码示例摘自一个为 Dictionary 类提供的更大的示例。

Visual Basic
' When a program often has to try keys that turn out not to
' be in the dictionary, TryGetValue can be a more efficient 
' way to retrieve values.
Dim value As String = ""
If openWith.TryGetValue("tif", value) Then
    Console.WriteLine("For key = ""tif"", value = {0}.", value)
Else
    Console.WriteLine("Key = ""tif"" is not found.")
End If
C#
// When a program often has to try keys that turn out not to
// be in the dictionary, TryGetValue can be a more efficient 
// way to retrieve values.
string value = "";
if (openWith.TryGetValue("tif", out value))
{
    Console.WriteLine("For key = \"tif\", value = {0}.", value);
}
else
{
    Console.WriteLine("Key = \"tif\" is not found.");
}

Windows 98、Windows 2000 SP4、Windows CE、Windows Millennium Edition、Windows Mobile for Pocket PC、Windows Mobile for Smartphone、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

.NET Framework

受以下版本支持:2.0

.NET Compact Framework

受以下版本支持:2.0
社区内容   什么是社区内容?
添加新内容 RSS  批注
Processing
© 2010 Microsoft Corporation 版权所有。 保留所有权利 | 商标 | 隐私权声明
Page view tracker