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則不會執行false任何操作,並且會傳回。If the key already exists, TryAdd does nothing and returns false.

適用於