[英]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;
第二个是使用具有默认项目名称( Item1
、 Item2
等)的未命名元组
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.