Joh*_* Wu 6 c# generics dictionary tuples
我知道我们可以声明一个命名元组,如:
var name = (first:"Sponge", last:"Bob");
Run Code Online (Sandbox Code Playgroud)
但是,我无法弄清楚如何将命名元组与泛型类型(例如 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;
Run Code Online (Sandbox Code Playgroud)
有谁知道 C# 是否支持上述场景?
你在这里有两个选择。第一个是在声明时使用自定义项目名称声明命名元组Dictionary,就像这样
var name = new Dictionary<string, (string value, string limitType)>();
name["cast"] = ("Sponge", "Bob"); //or name["cast"] = (value: "Sponge", limitType: "Bob");
Run Code Online (Sandbox Code Playgroud)
并通过以下方式访问项目
var value = name["cast"].value;
Run Code Online (Sandbox Code Playgroud)
第二个是使用默认的项目名称未命名的元组(Item1,Item2,等)
var name = new Dictionary<string, (string, string)>();
name["cast"] = ("Sponge", "Bob");
Run Code Online (Sandbox Code Playgroud)
C# 7 中添加了对元组的语言支持,请确保您使用的是该语言版本,或者安装System.ValueTuple包,如果缺少某些内容
| 归档时间: |
|
| 查看次数: |
1763 次 |
| 最近记录: |