Dictionary<TKey,TValue>.TryAdd(TKey, TValue) Dictionary<TKey,TValue>.TryAdd(TKey, TValue) Dictionary<TKey,TValue>.TryAdd(TKey, TValue) Dictionary<TKey,TValue>.TryAdd(TKey, TValue) Method

定义

尝试将指定的键和值添加到字典中。Attempts to add the specified key and value to the dictionary.

public:
 bool TryAdd(TKey key, TValue value);
public bool TryAdd (TKey key, TValue value);
member this.TryAdd : 'Key * 'Value -> bool
Public Function TryAdd (key As TKey, value As TValue) As Boolean

参数

key
TKey TKey TKey TKey

要添加的元素的键。The key of the element to add.

value
TValue TValue TValue TValue

要添加的元素的值。The value of the element to add. 它可能是 nullIt can be null.

返回

如果成功将键/值对添加到字典中,则为 true;否则为 falsetrue if the key/value pair was added to the dictionary successfully; otherwise, false.

异常

注解

Add与方法不同,如果字典中存在具有给定键的元素,则此方法不会引发异常。Unlike the Add method, this method doesn't throw an exception if the element with the given key exists in the dictionary. 与字典索引器不同TryAdd ,如果字典中存在具有给定键的元素,则不会重写元素。Unlike the Dictionary indexer, TryAdd doesn't override the element if the element with the given key exists in the dictionary. 如果该键已存在, TryAdd则不执行任何操作,并返回。 falseIf the key already exists, TryAdd does nothing and returns false.

适用于