命名空間:System.Collections.Generic
構造函數:public KeyValuePair (TKey key, TValue value);
屬性:只讀屬性 Key ,只讀屬性 Value
方法:public void Deconstruct (out TKey key, out TValue value);
方法 解構可以做模式匹配
public override string ToString ();
字符串表示形式,它包括鍵和值的字符串表示形式。
初始化,由於Key 、Value是只讀屬性,所以不能采用初始值設定項初始化,只能用構造函數初始化:
var kvp =new KeyValuePair<int, string> (3,"Command");
由於鍵值對有解構函數Deconstruct(record記錄也有解構函數)所以可以用作位模式匹配參數
支持switch表達式模式匹配 中的 屬性模式
static void Main(string[] args) { var kvp =new KeyValuePair<int, string> (3,"Command"); Console.WriteLine(keyPattrn(kvp)); } public static string keyPattrn(KeyValuePair<int, string> kvp) => kvp switch { (3, "Command") => "Origin", (4, "Command") => "Origin", _ => "Just a point", };
支持is表達式 中的 屬性模式
if(kvp is { Key: >2, Value: "Command" }) { Console.WriteLine("是的"); } if (kvp is (3, "Command")) { Console.WriteLine("是的"); } //輸出結果: // 是的 // 是的