【问题标题】:Is it possible to use named Tuple with generic type declaration?是否可以将命名元组与泛型类型声明一起使用?
【发布时间】:2020-06-20 06:22:38
【问题描述】:

我知道我们可以像这样声明一个命名元组:

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# 是否支持上述场景?

【问题讨论】:

    标签: c# dictionary generics tuples


    【解决方案1】:

    您有两个选择。第一个是在Dictionary 声明中使用自定义项目名称声明named tuple,就像这样

    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");
    

    Language support 用于元组是在 C# 7 中添加的,请确保您使用的是该语言版本,如果缺少某些内容,请安装 System.ValueTuple

    【讨论】:

    • 感谢 Pavel...唯一我没有尝试的是将名称放在类型之后...字符串值...给我我需要的...非常感谢!跨度>
    【解决方案2】:

    在这种情况下,重要的是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
    

    【讨论】:

      猜你喜欢
      • 2021-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多