使用英语阅读

通过


Dictionary<TKey,TValue>.Remove 方法

定义

重载

Remove(TKey)

Dictionary<TKey,TValue> 中移除所指定的键的值。

Remove(TKey, TValue)

Dictionary<TKey,TValue> 中删除具有指定键的值,并将元素复制到 value 参数。

Remove(TKey)

Source:
Dictionary.cs
Source:
Dictionary.cs
Source:
Dictionary.cs

Dictionary<TKey,TValue> 中移除所指定的键的值。

public bool Remove (TKey key);

参数

key
TKey

要移除的元素的键。

返回

如果成功找到并移除该元素,则为 true;否则为 false。 如果在 Dictionary<TKey,TValue> 中没有找到 key,则此方法返回 false

实现

例外

keynull

示例

下面的代码示例演示如何使用 Remove 方法从字典中删除键/值对。

此代码示例是为 Dictionary<TKey,TValue> 类提供的更大示例的一部分, openWith (是此示例中使用的字典的名称) 。

// Use the Remove method to remove a key/value pair.
Console.WriteLine("\nRemove(\"doc\")");
openWith.Remove("doc");

if (!openWith.ContainsKey("doc"))
{
    Console.WriteLine("Key \"doc\" is not found.");
}

注解

Dictionary<TKey,TValue>如果 不包含具有指定键的元素,则 Dictionary<TKey,TValue> 保持不变。 不会引发异常。

此方法用于处理 O (1) 操作。

仅限 .NET Core 3.0+:可以安全地调用此可变方法,而不会使实例上的 Dictionary<TKey,TValue> 活动枚举器失效。 这并不表示线程安全。

另请参阅

适用于

.NET 9 和其他版本
产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

Remove(TKey, TValue)

Source:
Dictionary.cs
Source:
Dictionary.cs
Source:
Dictionary.cs

Dictionary<TKey,TValue> 中删除具有指定键的值,并将元素复制到 value 参数。

public bool Remove (TKey key, out TValue value);

参数

key
TKey

要移除的元素的键。

value
TValue

已删除的元素。

返回

如果成功找到并移除该元素,则为 true;否则为 false

例外

keynull

适用于

.NET 9 和其他版本
产品 版本
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Standard 2.1