簡體   English   中英

是否可以將命名元組與泛型類型聲明一起使用?

[英]Is it possible to use named Tuple with generic type declaration?

我知道我們可以聲明一個命名元組,例如:

var name = (first:"Sponge", last:"Bob");

但是,我無法弄清楚如何將命名元組與泛型類型(例如 Dictionary )結合起來

我嘗試了以下變體,但沒有運氣:

Dictionary<string, (string, string)> name = new Dictionary<string, (string, string)>();

// this assignment yields this message:
// The tuple element name 'value' is ignored because a different name or no name is specified by the 
// target type '(string, string)'.
// The tuple element name 'limitType' is ignored because a different name or no name is specified 
// by the target type '(string, string)'.
name["cast"] = (value:"Sponge", limitType:"Bob");  

// I tried putting the name in front and at the end of the type, but no luck
// Both statements below produce syntactic error:
Dictionary<string, (value:string, string)> name;
Dictionary<string, (string:value, string)> name;

有誰知道 C# 是否支持上述場景?

你在這里有兩個選擇。 第一個是在Dictionary聲明中使用自定義項目名稱聲明命名元組,就像這樣

var name = new Dictionary<string, (string value, string limitType)>();
name["cast"] = ("Sponge", "Bob"); //or name["cast"] = (value: "Sponge", limitType: "Bob");

並通過以下方式訪問項目

var value = name["cast"].value;

第二個是使用具有默認項目名稱( Item1Item2等)的未命名元組

var name = new Dictionary<string, (string, string)>();
name["cast"] = ("Sponge", "Bob");

C# 7 中添加了對元組的語言支持,請確保您使用的是該語言版本,或者安裝System.ValueTuple包,如果缺少某些內容

在這種情況下,重要的是Dictionary聲明中的名稱:

Dictionary<string, (string First, string Last)> SomeDictionary
    = new Dictionary<string, (string, string)>();

然后你可以使用這樣的名字:

var value = SomeDictionary["SomeKey"];
var first = value.First;
var last = value.Last;
//var (first, last) = SomeDictionary["SomeKey"]; // alternative, Tuple deconstruction

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM