Create a new dictionary of strings, with string keys. // Dictionary openWith = new Dictionary(); // Add some elements to the ...
跳到主要內容
已不再支援此瀏覽器。
請升級至MicrosoftEdge,以利用最新功能、安全性更新和技術支援。
下載MicrosoftEdge
其他資訊
目錄
結束焦點模式
語言
儲存
編輯
共用
Twitter
LinkedIn
Facebook
電子郵件
WeChat
目錄
語言
Dictionary類別
定義
命名空間:
System.Collections.Generic
組件:System.Collections.dll
組件:mscorlib.dll,System.Collections.dll
組件:mscorlib.dll,netstandard.dll
組件:mscorlib.dll
組件:netstandard.dll
表示索引鍵和值的集合。
Representsacollectionofkeysandvalues.
本文內容
generic
publicrefclassDictionary:System::Collections::Generic::ICollection<:collections::generic::keyvaluepair>>,System::Collections::Generic::IDictionary,System::Collections::Generic::IEnumerable<:collections::generic::keyvaluepair>>,System::Collections::Generic::IReadOnlyCollection<:collections::generic::keyvaluepair>>,System::Collections::Generic::IReadOnlyDictionary,System::Collections::IDictionary
generic
publicrefclassDictionary:System::Collections::Generic::ICollection<:collections::generic::keyvaluepair>>,System::Collections::Generic::IDictionary,System::Collections::Generic::IEnumerable<:collections::generic::keyvaluepair>>,System::Collections::Generic::IReadOnlyCollection<:collections::generic::keyvaluepair>>,System::Collections::Generic::IReadOnlyDictionary,System::Collections::IDictionary,System::Runtime::Serialization::IDeserializationCallback,System::Runtime::Serialization::ISerializable
generic
publicrefclassDictionary:System::Collections::Generic::ICollection<:collections::generic::keyvaluepair>>,System::Collections::Generic::IDictionary,System::Collections::Generic::IEnumerable<:collections::generic::keyvaluepair>>,System::Collections::IDictionary,System::Runtime::Serialization::IDeserializationCallback,System::Runtime::Serialization::ISerializable
publicclassDictionary:System.Collections.Generic.ICollection>,System.Collections.Generic.IDictionary,System.Collections.Generic.IEnumerable>,System.Collections.Generic.IReadOnlyCollection>,System.Collections.Generic.IReadOnlyDictionary,System.Collections.IDictionary
publicclassDictionary:System.Collections.Generic.ICollection>,System.Collections.Generic.IDictionary,System.Collections.Generic.IEnumerable>,System.Collections.Generic.IReadOnlyCollection>,System.Collections.Generic.IReadOnlyDictionary,System.Collections.IDictionary,System.Runtime.Serialization.IDeserializationCallback,System.Runtime.Serialization.ISerializable
[System.Runtime.InteropServices.ComVisible(false)]
[System.Serializable]
publicclassDictionary:System.Collections.Generic.ICollection>,System.Collections.Generic.IDictionary,System.Collections.Generic.IEnumerable>,System.Collections.IDictionary,System.Runtime.Serialization.IDeserializationCallback,System.Runtime.Serialization.ISerializable
[System.Runtime.InteropServices.ComVisible(false)]
[System.Serializable]
publicclassDictionary:System.Collections.Generic.ICollection>,System.Collections.Generic.IDictionary,System.Collections.Generic.IEnumerable>,System.Collections.Generic.IReadOnlyCollection>,System.Collections.Generic.IReadOnlyDictionary,System.Collections.IDictionary,System.Runtime.Serialization.IDeserializationCallback,System.Runtime.Serialization.ISerializable
typeDictionary=class
interfaceICollection>
interfaceseq>
interfaceIEnumerable
interfaceIDictionary
interfaceIReadOnlyCollection>
interfaceIReadOnlyDictionary
interfaceICollection
interfaceIDictionary
typeDictionary=class
interfaceICollection>
interfaceseq>
interfaceIEnumerable
interfaceIDictionary
interfaceIReadOnlyCollection>
interfaceIReadOnlyDictionary
interfaceICollection
interfaceIDictionary
interfaceIDeserializationCallback
interfaceISerializable
[]
[]
typeDictionary=class
interfaceIDictionary
interfaceICollection>
interfaceseq>
interfaceIDictionary
interfaceICollection
interfaceIEnumerable
interfaceISerializable
interfaceIDeserializationCallback
[]
[]
typeDictionary=class
interfaceIDictionary
interfaceICollection>
interfaceIDictionary
interfaceICollection
interfaceIReadOnlyDictionary
interfaceIReadOnlyCollection>
interfaceseq>
interfaceIEnumerable
interfaceISerializable
interfaceIDeserializationCallback
[]
[]
typeDictionary=class
interfaceIDictionary
interfaceICollection>
interfaceseq>
interfaceIEnumerable
interfaceIDictionary
interfaceICollection
interfaceIReadOnlyDictionary
interfaceIReadOnlyCollection>
interfaceISerializable
interfaceIDeserializationCallback
typeDictionary=class
interfaceIDictionary
interfaceICollection>
interfaceIReadOnlyDictionary
interfaceIReadOnlyCollection>
interfaceseq>
interfaceIDictionary
interfaceICollection
interfaceIEnumerable
[]
[]
typeDictionary=class
interfaceIDictionary
interfaceIDictionary
interfaceIReadOnlyDictionary
interfaceISerializable
interfaceIDeserializationCallback
interfaceICollection>
interfaceseq>
interfaceIEnumerable
interfaceICollection
interfaceIReadOnlyCollection>
PublicClassDictionary(OfTKey,TValue)
ImplementsICollection(OfKeyValuePair(OfTKey,TValue)),IDictionary,IDictionary(OfTKey,TValue),IEnumerable(OfKeyValuePair(OfTKey,TValue)),IReadOnlyCollection(OfKeyValuePair(OfTKey,TValue)),IReadOnlyDictionary(OfTKey,TValue)
PublicClassDictionary(OfTKey,TValue)
ImplementsICollection(OfKeyValuePair(OfTKey,TValue)),IDeserializationCallback,IDictionary,IDictionary(OfTKey,TValue),IEnumerable(OfKeyValuePair(OfTKey,TValue)),IReadOnlyCollection(OfKeyValuePair(OfTKey,TValue)),IReadOnlyDictionary(OfTKey,TValue),ISerializable
PublicClassDictionary(OfTKey,TValue)
ImplementsICollection(OfKeyValuePair(OfTKey,TValue)),IDeserializationCallback,IDictionary,IDictionary(OfTKey,TValue),IEnumerable(OfKeyValuePair(OfTKey,TValue)),ISerializable
類型參數
TKey
字典中的索引鍵類型。
Thetypeofthekeysinthedictionary.
TValue
字典中的值類型。
Thetypeofthevaluesinthedictionary.
繼承
Object
Dictionary
衍生
System.ServiceModel.MessageQuerySet
屬性
ComVisibleAttribute
SerializableAttribute
實作
ICollection>
IDictionary
IEnumerable>
IEnumerable
IReadOnlyCollection>
IReadOnlyDictionary
ICollection
IDictionary
IEnumerable
IDeserializationCallback
ISerializable
範例
下列程式碼範例會使用字串索引鍵建立空Dictionary的字串,並使用Add方法來加入一些元素。
ThefollowingcodeexamplecreatesanemptyDictionaryofstringswithstringkeysandusestheAddmethodtoaddsomeelements.此範例示範AddArgumentException當嘗試加入重複的索引鍵時,方法會擲回。
TheexampledemonstratesthattheAddmethodthrowsanArgumentExceptionwhenattemptingtoaddaduplicatekey.
此範例會使用Item[]屬性(c#中的索引子)來取得值,KeyNotFoundException並示範當要求的索引鍵不存在時擲回,並顯示與索引鍵相關聯的值可以取代。
TheexampleusestheItem[]property(theindexerinC#)toretrievevalues,demonstratingthataKeyNotFoundExceptionisthrownwhenarequestedkeyisnotpresent,andshowingthatthevalueassociatedwithakeycanbereplaced.
該示例顯示如何使用TryGetValue方法作為更有效的方式來檢索值,如果程序通常必須嘗試不在字典中的鍵值,並且它顯示如何使用ContainsKey方法來測試在調用Add方法。
TheexampleshowshowtousetheTryGetValuemethodasamoreefficientwaytoretrievevaluesifaprogramoftenmusttrykeyvaluesthatarenotinthedictionary,anditshowshowtousetheContainsKeymethodtotestwhetherakeyexistsbeforecallingtheAddmethod.
此範例顯示如何列舉字典中的索引鍵和值,以及如何使用屬性和屬性單獨列舉索引鍵和值KeysValues。
TheexampleshowshowtoenumeratethekeysandvaluesinthedictionaryandhowtoenumeratethekeysandvaluesaloneusingtheKeyspropertyandtheValuesproperty.
最後,此範例會示範Remove方法。
Finally,theexampledemonstratestheRemovemethod.
usingnamespaceSystem;
usingnamespaceSystem::Collections::Generic;
publicrefclassExample
{
public:
staticvoidMain()
{
//Createanewdictionaryofstrings,withstringkeys.
//
Dictionary^openWith=
gcnewDictionary();
//Addsomeelementstothedictionary.Thereareno
//duplicatekeys,butsomeofthevaluesareduplicates.
openWith->Add("txt","notepad.exe");
openWith->Add("bmp","paint.exe");
openWith->Add("dib","paint.exe");
openWith->Add("rtf","wordpad.exe");
//TheAddmethodthrowsanexceptionifthenewkeyis
//alreadyinthedictionary.
try
{
openWith->Add("txt","winword.exe");
}
catch(ArgumentException^)
{
Console::WriteLine("AnelementwithKey=\"txt\"alreadyexists.");
}
//TheItempropertyisanothernamefortheindexer,soyou
//canomititsnamewhenaccessingelements.
Console::WriteLine("Forkey=\"rtf\",value={0}.",
openWith["rtf"]);
//Theindexercanbeusedtochangethevalueassociated
//withakey.
openWith["rtf"]="winword.exe";
Console::WriteLine("Forkey=\"rtf\",value={0}.",
openWith["rtf"]);
//Ifakeydoesnotexist,settingtheindexerforthatkey
//addsanewkey/valuepair.
openWith["doc"]="winword.exe";
//Theindexerthrowsanexceptioniftherequestedkeyis
//notinthedictionary.
try
{
Console::WriteLine("Forkey=\"tif\",value={0}.",
openWith["tif"]);
}
catch(KeyNotFoundException^)
{
Console::WriteLine("Key=\"tif\"isnotfound.");
}
//Whenaprogramoftenhastotrykeysthatturnoutnotto
//beinthedictionary,TryGetValuecanbeamoreefficient
//waytoretrievevalues.
String^value="";
if(openWith->TryGetValue("tif",value))
{
Console::WriteLine("Forkey=\"tif\",value={0}.",value);
}
else
{
Console::WriteLine("Key=\"tif\"isnotfound.");
}
//ContainsKeycanbeusedtotestkeysbeforeinserting
//them.
if(!openWith->ContainsKey("ht"))
{
openWith->Add("ht","hypertrm.exe");
Console::WriteLine("Valueaddedforkey=\"ht\":{0}",
openWith["ht"]);
}
//Whenyouuseforeachtoenumeratedictionaryelements,
//theelementsareretrievedasKeyValuePairobjects.
Console::WriteLine();
foreach(KeyValuePairkvpinopenWith)
{
Console::WriteLine("Key={0},Value={1}",
kvp.Key,kvp.Value);
}
//Togetthevaluesalone,usetheValuesproperty.
Dictionary::ValueCollection^valueColl=
openWith->Values;
//TheelementsoftheValueCollectionarestronglytyped
//withthetypethatwasspecifiedfordictionaryvalues.
Console::WriteLine();
foreach(String^sinvalueColl)
{
Console::WriteLine("Value={0}",s);
}
//Togetthekeysalone,usetheKeysproperty.
Dictionary::KeyCollection^keyColl=
openWith->Keys;
//TheelementsoftheKeyCollectionarestronglytyped
//withthetypethatwasspecifiedfordictionarykeys.
Console::WriteLine();
foreach(String^sinkeyColl)
{
Console::WriteLine("Key={0}",s);
}
//UsetheRemovemethodtoremoveakey/valuepair.
Console::WriteLine("\nRemove(\"doc\")");
openWith->Remove("doc");
if(!openWith->ContainsKey("doc"))
{
Console::WriteLine("Key\"doc\"isnotfound.");
}
}
};
intmain()
{
Example::Main();
}
/*Thiscodeexampleproducesthefollowingoutput:
AnelementwithKey="txt"alreadyexists.
Forkey="rtf",value=wordpad.exe.
Forkey="rtf",value=winword.exe.
Key="tif"isnotfound.
Key="tif"isnotfound.
Valueaddedforkey="ht":hypertrm.exe
Key=txt,Value=notepad.exe
Key=bmp,Value=paint.exe
Key=dib,Value=paint.exe
Key=rtf,Value=winword.exe
Key=doc,Value=winword.exe
Key=ht,Value=hypertrm.exe
Value=notepad.exe
Value=paint.exe
Value=paint.exe
Value=winword.exe
Value=winword.exe
Value=hypertrm.exe
Key=txt
Key=bmp
Key=dib
Key=rtf
Key=doc
Key=ht
Remove("doc")
Key"doc"isnotfound.
*/
//Createanewdictionaryofstrings,withstringkeys.
//
DictionaryopenWith=
newDictionary();
//Addsomeelementstothedictionary.Thereareno
//duplicatekeys,butsomeofthevaluesareduplicates.
openWith.Add("txt","notepad.exe");
openWith.Add("bmp","paint.exe");
openWith.Add("dib","paint.exe");
openWith.Add("rtf","wordpad.exe");
//TheAddmethodthrowsanexceptionifthenewkeyis
//alreadyinthedictionary.
try
{
openWith.Add("txt","winword.exe");
}
catch(ArgumentException)
{
Console.WriteLine("AnelementwithKey=\"txt\"alreadyexists.");
}
//TheItempropertyisanothernamefortheindexer,soyou
//canomititsnamewhenaccessingelements.
Console.WriteLine("Forkey=\"rtf\",value={0}.",
openWith["rtf"]);
//Theindexercanbeusedtochangethevalueassociated
//withakey.
openWith["rtf"]="winword.exe";
Console.WriteLine("Forkey=\"rtf\",value={0}.",
openWith["rtf"]);
//Ifakeydoesnotexist,settingtheindexerforthatkey
//addsanewkey/valuepair.
openWith["doc"]="winword.exe";
//Theindexerthrowsanexceptioniftherequestedkeyis
//notinthedictionary.
try
{
Console.WriteLine("Forkey=\"tif\",value={0}.",
openWith["tif"]);
}
catch(KeyNotFoundException)
{
Console.WriteLine("Key=\"tif\"isnotfound.");
}
//Whenaprogramoftenhastotrykeysthatturnoutnotto
//beinthedictionary,TryGetValuecanbeamoreefficient
//waytoretrievevalues.
stringvalue="";
if(openWith.TryGetValue("tif",outvalue))
{
Console.WriteLine("Forkey=\"tif\",value={0}.",value);
}
else
{
Console.WriteLine("Key=\"tif\"isnotfound.");
}
//ContainsKeycanbeusedtotestkeysbeforeinserting
//them.
if(!openWith.ContainsKey("ht"))
{
openWith.Add("ht","hypertrm.exe");
Console.WriteLine("Valueaddedforkey=\"ht\":{0}",
openWith["ht"]);
}
//Whenyouuseforeachtoenumeratedictionaryelements,
//theelementsareretrievedasKeyValuePairobjects.
Console.WriteLine();
foreach(KeyValuePairkvpinopenWith)
{
Console.WriteLine("Key={0},Value={1}",
kvp.Key,kvp.Value);
}
//Togetthevaluesalone,usetheValuesproperty.
Dictionary.ValueCollectionvalueColl=
openWith.Values;
//TheelementsoftheValueCollectionarestronglytyped
//withthetypethatwasspecifiedfordictionaryvalues.
Console.WriteLine();
foreach(stringsinvalueColl)
{
Console.WriteLine("Value={0}",s);
}
//Togetthekeysalone,usetheKeysproperty.
Dictionary.KeyCollectionkeyColl=
openWith.Keys;
//TheelementsoftheKeyCollectionarestronglytyped
//withthetypethatwasspecifiedfordictionarykeys.
Console.WriteLine();
foreach(stringsinkeyColl)
{
Console.WriteLine("Key={0}",s);
}
//UsetheRemovemethodtoremoveakey/valuepair.
Console.WriteLine("\nRemove(\"doc\")");
openWith.Remove("doc");
if(!openWith.ContainsKey("doc"))
{
Console.WriteLine("Key\"doc\"isnotfound.");
}
/*Thiscodeexampleproducesthefollowingoutput:
AnelementwithKey="txt"alreadyexists.
Forkey="rtf",value=wordpad.exe.
Forkey="rtf",value=winword.exe.
Key="tif"isnotfound.
Key="tif"isnotfound.
Valueaddedforkey="ht":hypertrm.exe
Key=txt,Value=notepad.exe
Key=bmp,Value=paint.exe
Key=dib,Value=paint.exe
Key=rtf,Value=winword.exe
Key=doc,Value=winword.exe
Key=ht,Value=hypertrm.exe
Value=notepad.exe
Value=paint.exe
Value=paint.exe
Value=winword.exe
Value=winword.exe
Value=hypertrm.exe
Key=txt
Key=bmp
Key=dib
Key=rtf
Key=doc
Key=ht
Remove("doc")
Key"doc"isnotfound.
*/
ImportsSystem.Collections.Generic
PublicClassExample
PublicSharedSubMain()
'Createanewdictionaryofstrings,withstringkeys.
'
DimopenWithAsNewDictionary(OfString,String)
'Addsomeelementstothedictionary.Thereareno
'duplicatekeys,butsomeofthevaluesareduplicates.
openWith.Add("txt","notepad.exe")
openWith.Add("bmp","paint.exe")
openWith.Add("dib","paint.exe")
openWith.Add("rtf","wordpad.exe")
'TheAddmethodthrowsanexceptionifthenewkeyis
'alreadyinthedictionary.
Try
openWith.Add("txt","winword.exe")
Catch
Console.WriteLine("AnelementwithKey=""txt""alreadyexists.")
EndTry
'TheItempropertyisthedefaultproperty,soyou
'canomititsnamewhenaccessingelements.
Console.WriteLine("Forkey=""rtf"",value={0}.",_
openWith("rtf"))
'ThedefaultItempropertycanbeusedtochangethevalue
'associatedwithakey.
openWith("rtf")="winword.exe"
Console.WriteLine("Forkey=""rtf"",value={0}.",_
openWith("rtf"))
'Ifakeydoesnotexist,settingthedefaultItemproperty
'forthatkeyaddsanewkey/valuepair.
openWith("doc")="winword.exe"
'ThedefaultItempropertythrowsanexceptioniftherequested
'keyisnotinthedictionary.
Try
Console.WriteLine("Forkey=""tif"",value={0}.",_
openWith("tif"))
Catch
Console.WriteLine("Key=""tif""isnotfound.")
EndTry
'Whenaprogramoftenhastotrykeysthatturnoutnotto
'beinthedictionary,TryGetValuecanbeamoreefficient
'waytoretrievevalues.
DimvalueAsString=""
IfopenWith.TryGetValue("tif",value)Then
Console.WriteLine("Forkey=""tif"",value={0}.",value)
Else
Console.WriteLine("Key=""tif""isnotfound.")
EndIf
'ContainsKeycanbeusedtotestkeysbeforeinserting
'them.
IfNotopenWith.ContainsKey("ht")Then
openWith.Add("ht","hypertrm.exe")
Console.WriteLine("Valueaddedforkey=""ht"":{0}",_
openWith("ht"))
EndIf
'Whenyouuseforeachtoenumeratedictionaryelements,
'theelementsareretrievedasKeyValuePairobjects.
Console.WriteLine()
ForEachkvpAsKeyValuePair(OfString,String)InopenWith
Console.WriteLine("Key={0},Value={1}",_
kvp.Key,kvp.Value)
Nextkvp
'Togetthevaluesalone,usetheValuesproperty.
DimvalueCollAs_
Dictionary(OfString,String).ValueCollection=_
openWith.Values
'TheelementsoftheValueCollectionarestronglytyped
'withthetypethatwasspecifiedfordictionaryvalues.
Console.WriteLine()
ForEachsAsStringInvalueColl
Console.WriteLine("Value={0}",s)
Nexts
'Togetthekeysalone,usetheKeysproperty.
DimkeyCollAs_
Dictionary(OfString,String).KeyCollection=_
openWith.Keys
'TheelementsoftheKeyCollectionarestronglytyped
'withthetypethatwasspecifiedfordictionarykeys.
Console.WriteLine()
ForEachsAsStringInkeyColl
Console.WriteLine("Key={0}",s)
Nexts
'UsetheRemovemethodtoremoveakey/valuepair.
Console.WriteLine(vbLf+"Remove(""doc"")")
openWith.Remove("doc")
IfNotopenWith.ContainsKey("doc")Then
Console.WriteLine("Key""doc""isnotfound.")
EndIf
EndSub
EndClass
'Thiscodeexampleproducesthefollowingoutput:
'
'AnelementwithKey="txt"alreadyexists.
'Forkey="rtf",value=wordpad.exe.
'Forkey="rtf",value=winword.exe.
'Key="tif"isnotfound.
'Key="tif"isnotfound.
'Valueaddedforkey="ht":hypertrm.exe
'
'Key=txt,Value=notepad.exe
'Key=bmp,Value=paint.exe
'Key=dib,Value=paint.exe
'Key=rtf,Value=winword.exe
'Key=doc,Value=winword.exe
'Key=ht,Value=hypertrm.exe
'
'Value=notepad.exe
'Value=paint.exe
'Value=paint.exe
'Value=winword.exe
'Value=winword.exe
'Value=hypertrm.exe
'
'Key=txt
'Key=bmp
'Key=dib
'Key=rtf
'Key=doc
'Key=ht
'
'Remove("doc")
'Key"doc"isnotfound.
'
備註
Dictionary泛型類別會提供一組索引鍵與一組值的對應。
TheDictionarygenericclassprovidesamappingfromasetofkeystoasetofvalues.加入字典中的每一個項目都是由值及其關聯索引鍵所組成。
Eachadditiontothedictionaryconsistsofavalueanditsassociatedkey.使用索引鍵來抓取值相當快速,接近O(1),因為該Dictionary類別會實作為雜湊表。
Retrievingavaluebyusingitskeyisveryfast,closetoO(1),becausetheDictionaryclassisimplementedasahashtable.
注意
抓取的速度取決於所指定之類型的雜湊演算法品質TKey。
ThespeedofretrievaldependsonthequalityofthehashingalgorithmofthetypespecifiedforTKey.
只要將物件當做中的索引鍵使用Dictionary,它就不能以任何影響其雜湊值的方式變更。
AslongasanobjectisusedasakeyintheDictionary,itmustnotchangeinanywaythataffectsitshashvalue.中的每個索引鍵都Dictionary必須是唯一的,根據字典的相等比較子。
EverykeyinaDictionarymustbeuniqueaccordingtothedictionary'sequalitycomparer.索引鍵不能是null,但如果其型別TValue是參考型別,則其值可以是。
Akeycannotbenull,butavaluecanbe,ifitstypeTValueisareferencetype.
Dictionary需要相等的執行,以判斷索引鍵是否相等。
Dictionaryrequiresanequalityimplementationtodeterminewhetherkeysareequal.您可以使用接受參數的函式來指定泛型介面的實值IEqualityComparercomparer;如果您沒有指定執行,則會使用預設的泛型相等比較子EqualityComparer.Default。
YoucanspecifyanimplementationoftheIEqualityComparergenericinterfacebyusingaconstructorthatacceptsacomparerparameter;ifyoudonotspecifyanimplementation,thedefaultgenericequalitycomparerEqualityComparer.Defaultisused.如果類型TKeySystem.IEquatable會實作為泛型介面,則預設的相等比較子會使用該執行。
IftypeTKeyimplementstheSystem.IEquatablegenericinterface,thedefaultequalitycomparerusesthatimplementation.
注意
例如,您可以使用類別提供的不區分大小寫字串比較子StringComparer來建立具有不區分大小寫字串索引鍵的字典。
Forexample,youcanusethecase-insensitivestringcomparersprovidedbytheStringComparerclasstocreatedictionarieswithcase-insensitivestringkeys.
的容量Dictionary是可保存的元素數目Dictionary。
ThecapacityofaDictionaryisthenumberofelementstheDictionarycanhold.當專案加入至時Dictionary,會依需要重新配置內部陣列來自動增加容量。
AselementsareaddedtoaDictionary,thecapacityisautomaticallyincreasedasrequiredbyreallocatingtheinternalarray.
僅.NETFramework:針對非常大的Dictionary物件,您可以在enabledtrue執行時間環境中將設定元素的屬性設定為,以增加64位系統上2000000000元素的最大容量。
.NETFrameworkonly:ForverylargeDictionaryobjects,youcanincreasethemaximumcapacityto2billionelementsona64-bitsystembysettingtheenabledattributeoftheconfigurationelementtotrueintherun-timeenvironment.
基於列舉的目的,字典中的每個專案都會被視為KeyValuePair代表值和其索引鍵的結構。
Forpurposesofenumeration,eachiteminthedictionaryistreatedasaKeyValuePairstructurerepresentingavalueanditskey.傳回專案的順序未定義。
Theorderinwhichtheitemsarereturnedisundefined.
Cforeach++中的c#語言(的語句foreach,ForEach在VisualBasic)會傳回集合中元素類型的物件。
TheforeachstatementoftheC#language(foreachinC++,ForEachinVisualBasic)returnsanobjectofthetypeoftheelementsinthecollection.由於Dictionary是索引鍵和值的集合,因此元素類型不是索引鍵的類型或值的型別。
SincetheDictionaryisacollectionofkeysandvalues,theelementtypeisnotthetypeofthekeyorthetypeofthevalue.相反地,元素類型是索引KeyValuePair鍵類型和數值型別的。
Instead,theelementtypeisaKeyValuePairofthekeytypeandthevaluetype.例如:Forexample:
foreach(KeyValuePairkvpinmyDictionary)
{
Console::WriteLine("Key={0},Value={1}",kvp.Key,kvp.Value);
}
foreach(KeyValuePairkvpinmyDictionary)
{
Console.WriteLine("Key={0},Value={1}",kvp.Key,kvp.Value);
}
ForEachkvpAsKeyValuePair(OfString,String)InmyDictionary
Console.WriteLine("Key={0},Value={1}",kvp.Key,kvp.Value)
Nextkvp
foreach語句是列舉值周圍的包裝函式,它只允許從集合讀取,而不是寫入它。
Theforeachstatementisawrapperaroundtheenumerator,whichallowsonlyreadingfromthecollection,notwritingtoit.
注意
因為索引鍵可以繼承並變更其行為,所以使用方法的比較無法保證其絕對唯一性Equals。
Becausekeyscanbeinheritedandtheirbehaviorchanged,theirabsoluteuniquenesscannotbeguaranteedbycomparisonsusingtheEqualsmethod.
建構函式
Dictionary()
初始化Dictionary類別的新執行個體,這個執行個體是空白的、具有預設的初始容量,並使用索引鍵類型的預設相等比較子。
InitializesanewinstanceoftheDictionaryclassthatisempty,hasthedefaultinitialcapacity,andusesthedefaultequalitycomparerforthekeytype.
Dictionary(IDictionary)
初始化Dictionary類別的新執行個體,其中包含從指定的IDictionary複製的項目,並使用索引鍵類型的預設相等比較子。
InitializesanewinstanceoftheDictionaryclassthatcontainselementscopiedfromthespecifiedIDictionaryandusesthedefaultequalitycomparerforthekeytype.
Dictionary(IDictionary,IEqualityComparer)
初始化Dictionary類別的新執行個體,其中包含從指定的IDictionary複製的項目,並使用指定的IEqualityComparer。
InitializesanewinstanceoftheDictionaryclassthatcontainselementscopiedfromthespecifiedIDictionaryandusesthespecifiedIEqualityComparer.
Dictionary(IEnumerable>)
初始化Dictionary類別的新執行個體,這個類別包含從指定的IEnumerable所複製項目。
InitializesanewinstanceoftheDictionaryclassthatcontainselementscopiedfromthespecifiedIEnumerable.
Dictionary(IEnumerable>,IEqualityComparer)
初始化Dictionary類別的新執行個體,其中包含從指定的IEnumerable複製的項目,並使用指定的IEqualityComparer。
InitializesanewinstanceoftheDictionaryclassthatcontainselementscopiedfromthespecifiedIEnumerableandusesthespecifiedIEqualityComparer.
Dictionary(IEqualityComparer)
初始化Dictionary類別的新執行個體,這個執行個體是空白的、具有預設的初始容量,並使用指定的IEqualityComparer。
InitializesanewinstanceoftheDictionaryclassthatisempty,hasthedefaultinitialcapacity,andusesthespecifiedIEqualityComparer.
Dictionary(Int32)
初始化Dictionary類別的新執行個體,這個執行個體是空白的、具有指定的初始容量,並使用索引鍵類型的預設相等比較子。
InitializesanewinstanceoftheDictionaryclassthatisempty,hasthespecifiedinitialcapacity,andusesthedefaultequalitycomparerforthekeytype.
Dictionary(Int32,IEqualityComparer)
初始化Dictionary類別的新執行個體,這個執行個體是空白的、具有指定的初始容量,並使用指定的IEqualityComparer。
InitializesanewinstanceoftheDictionaryclassthatisempty,hasthespecifiedinitialcapacity,andusesthespecifiedIEqualityComparer.
Dictionary(SerializationInfo,StreamingContext)
使用序列化資料,初始化Dictionary類別的新執行個體。
InitializesanewinstanceoftheDictionaryclasswithserializeddata.
屬性
Comparer
取得IEqualityComparer,用來判斷字典的索引鍵是否相等。
GetstheIEqualityComparerthatisusedtodetermineequalityofkeysforthedictionary.
Count
取得Dictionary中所包含的索引鍵/值組數目。
Getsthenumberofkey/valuepairscontainedintheDictionary.
Item[TKey]
取得或設定與指定之索引鍵相關聯的值。
Getsorsetsthevalueassociatedwiththespecifiedkey.
Keys
取得集合,包含Dictionary中的索引鍵。
GetsacollectioncontainingthekeysintheDictionary.
Values
取得集合,包含Dictionary中的值。
GetsacollectioncontainingthevaluesintheDictionary.
方法
Add(TKey,TValue)
將指定的索引鍵和值加入字典。
Addsthespecifiedkeyandvaluetothedictionary.
Clear()
從Dictionary移除所有索引鍵和值。
RemovesallkeysandvaluesfromtheDictionary.
ContainsKey(TKey)
判斷Dictionary是否包含特定索引鍵。
DetermineswhethertheDictionarycontainsthespecifiedkey.
ContainsValue(TValue)
判斷Dictionary是否包含特定值。
DetermineswhethertheDictionarycontainsaspecificvalue.
EnsureCapacity(Int32)
確保字典最多可以保留指定的項目數量,但不必進一步擴充其支援儲存體。
Ensuresthatthedictionarycanholduptoaspecifiednumberofentrieswithoutanyfurtherexpansionofitsbackingstorage.
Equals(Object)
判斷指定的物件是否等於目前的物件。
Determineswhetherthespecifiedobjectisequaltothecurrentobject.
(繼承來源Object)
GetEnumerator()
傳回在Dictionary中逐一查看的列舉值。
ReturnsanenumeratorthatiteratesthroughtheDictionary.
GetHashCode()
做為預設雜湊函式。
Servesasthedefaulthashfunction.
(繼承來源Object)
GetObjectData(SerializationInfo,StreamingContext)
實作ISerializable介面,並傳回序列化Dictionary執行個體所需的資料。
ImplementstheISerializableinterfaceandreturnsthedataneededtoserializetheDictionaryinstance.
GetType()
取得目前執行個體的Type。
GetstheTypeofthecurrentinstance.
(繼承來源Object)
MemberwiseClone()
建立目前Object的淺層複製。
CreatesashallowcopyofthecurrentObject.
(繼承來源Object)
OnDeserialization(Object)
實作ISerializable介面,並於還原序列化完成時引發還原序列化事件。
ImplementstheISerializableinterfaceandraisesthedeserializationeventwhenthedeserializationiscomplete.
Remove(TKey)
將具有指定索引鍵的值從Dictionary中移除。
RemovesthevaluewiththespecifiedkeyfromtheDictionary.
Remove(TKey,TValue)
從Dictionary中移除具有指定索引鍵的值,並將該項目複製到value參數。
RemovesthevaluewiththespecifiedkeyfromtheDictionary,andcopiestheelementtothevalueparameter.
ToString()
傳回代表目前物件的字串。
Returnsastringthatrepresentsthecurrentobject.
(繼承來源Object)
TrimExcess()
將此字典容量設定為一開始若使用所有項目初始化的應有容量。
Setsthecapacityofthisdictionarytowhatitwouldbeifithadbeenoriginallyinitializedwithallitsentries.
TrimExcess(Int32)
將此字典容量設定為最多可以保留的指定項目數量,但不必進一步擴充其支援儲存體。
Setsthecapacityofthisdictionarytoholdupaspecifiednumberofentrieswithoutanyfurtherexpansionofitsbackingstorage.
TryAdd(TKey,TValue)
嘗試將指定的索引鍵和值新增至字典。
Attemptstoaddthespecifiedkeyandvaluetothedictionary.
TryGetValue(TKey,TValue)
取得與指定索引鍵關聯的值。
Getsthevalueassociatedwiththespecifiedkey.
明確介面實作
ICollection.CopyTo(Array,Int32)
從指定的陣列索引處開始,將ICollection的項目複製到陣列。
CopiestheelementsoftheICollectiontoanarray,startingatthespecifiedarrayindex.
ICollection.IsSynchronized
取得值,這個值會指出ICollection的存取是否同步(具備安全執行緒)。
GetsavaluethatindicateswhetheraccesstotheICollectionissynchronized(threadsafe).
ICollection.SyncRoot
取得可用以同步存取ICollection的物件。
GetsanobjectthatcanbeusedtosynchronizeaccesstotheICollection.
ICollection>.Add(KeyValuePair)
將指定的值加入具有指定索引鍵的ICollection。
AddsthespecifiedvaluetotheICollectionwiththespecifiedkey.
ICollection>.Contains(KeyValuePair)
判斷ICollection是否包含特定索引鍵和值。
DetermineswhethertheICollectioncontainsaspecifickeyandvalue.
ICollection>.CopyTo(KeyValuePair[],Int32)
從指定的陣列索引處開始,將ICollection的項目複製到KeyValuePair類型的陣列。
CopiestheelementsoftheICollectiontoanarrayoftypeKeyValuePair,startingatthespecifiedarrayindex.
ICollection>.IsReadOnly
取得值,這個值表示字典是否為唯讀。
Getsavaluethatindicateswhetherthedictionaryisread-only.
ICollection>.Remove(KeyValuePair)
從字典移除索引鍵和值。
Removesakeyandvaluefromthedictionary.
IDictionary.Add(Object,Object)
將指定的索引鍵和值加入字典。
Addsthespecifiedkeyandvaluetothedictionary.
IDictionary.Contains(Object)
判斷IDictionary是否包含具有指定之索引鍵的項目。
DetermineswhethertheIDictionarycontainsanelementwiththespecifiedkey.
IDictionary.GetEnumerator()
傳回IDictionaryEnumerator的IDictionary。
ReturnsanIDictionaryEnumeratorfortheIDictionary.
IDictionary.IsFixedSize
取得值,指出IDictionary是否有固定的大小。
GetsavaluethatindicateswhethertheIDictionaryhasafixedsize.
IDictionary.IsReadOnly
取得值,這個值表示IDictionary是否為唯讀。
GetsavaluethatindicateswhethertheIDictionaryisread-only.
IDictionary.Item[Object]
取得或設定具有指定之索引鍵的值。
Getsorsetsthevaluewiththespecifiedkey.
IDictionary.Keys
取得ICollection,包含IDictionary的索引鍵。
GetsanICollectioncontainingthekeysoftheIDictionary.
IDictionary.Remove(Object)
從IDictionary中移除具有指定之索引鍵的項目。
RemovestheelementwiththespecifiedkeyfromtheIDictionary.
IDictionary.Values
取得ICollection,包含IDictionary中的值。
GetsanICollectioncontainingthevaluesintheIDictionary.
IDictionary.Keys
取得ICollection,包含IDictionary的索引鍵。
GetsanICollectioncontainingthekeysoftheIDictionary.
IDictionary.Values
取得ICollection,包含IDictionary中的值。
GetsanICollectioncontainingthevaluesintheIDictionary.
IEnumerable.GetEnumerator()
傳回逐一查看集合的列舉值。
Returnsanenumeratorthatiteratesthroughthecollection.
IEnumerable>.GetEnumerator()
傳回逐一查看集合的列舉值。
Returnsanenumeratorthatiteratesthroughthecollection.
IReadOnlyDictionary.Keys
取得集合,其中包含IReadOnlyDictionary的索引鍵。
GetsacollectioncontainingthekeysoftheIReadOnlyDictionary.
IReadOnlyDictionary.Values
取得集合,其中包含IReadOnlyDictionary的值。
GetsacollectioncontainingthevaluesoftheIReadOnlyDictionary.
擴充方法
GetValueOrDefault(IReadOnlyDictionary,TKey)
嘗試取得與dictionary中所指定key建立關聯的值。
Triestogetthevalueassociatedwiththespecifiedkeyinthedictionary.
GetValueOrDefault(IReadOnlyDictionary,TKey,TValue)
嘗試取得與dictionary中所指定索引鍵建立關聯的值。
Triestogetthevalueassociatedwiththespecifiedkeyinthedictionary.
Remove(IDictionary,TKey,TValue)
嘗試從dictionary中移除具有所指定key的值。
Triestoremovethevaluewiththespecifiedkeyfromthedictionary.
TryAdd(IDictionary,TKey,TValue)
嘗試將指定的key和value新增至dictionary。
Triestoaddthespecifiedkeyandvaluetothedictionary.
ToImmutableArray(IEnumerable)
從指定的集合建立不可變的陣列。
Createsanimmutablearrayfromthespecifiedcollection.
ToImmutableDictionary(IEnumerable,Func)
從現有的項目集合建構不可變的字典,將轉換函式套用至來源索引鍵。
Constructsanimmutabledictionaryfromanexistingcollectionofelements,applyingatransformationfunctiontothesourcekeys.
ToImmutableDictionary(IEnumerable,Func,IEqualityComparer)
根據序列的某些轉換來建構不可變的字典。
Constructsanimmutabledictionarybasedonsometransformationofasequence.
ToImmutableDictionary(IEnumerable