【问题标题】:How do I declare a Dictionary in VB.Net with a string key and a named Tuple as the value?如何在 VB.Net 中使用字符串键和命名元组作为值声明字典?
【发布时间】:2021-09-07 16:05:37
【问题描述】:

我正在声明一个数据结构并用数据加载它

    Public Shared LexerEnglishFullWithTuple As New Dictionary(Of String, Object) From {
{"LET", (1, "000000001", 0)},
{"PUT", (2, "000000002", 2)},
...

我想做的是为 ValueTuple 的组件命名,并且在一定程度上这是可行的,即,

    Public Shared LexerEnglishFullWithTuple As New Dictionary(Of String, Object) From {
{"LET", (Id:=1, IdString:="000000001", Arity:=0)},
{"PUT", (Id:=2, IdString:="000000002", Arity:=2)},
...

我现在坚持的是As New Dictionary(Of String, Object),如果能够放置 Object 以外的东西会很好。我已经尝试过TupleValueTuple 和各种(Of 之类的东西,但似乎没有任何东西可以编译。

在我的测试中,因为只是Of String,Object看不到Id、IdString和Arity,所以只能看到Item1、Item2和Item3

        <Fact>
        Sub TestSub2()
            Dim FEL = Lexers.English.LexerEnglishFullWithTuple
            Dim x = FEL("EDS")
            Dim y = From el In FEL Where el.Value.Item1 = 861220001 Select el.Key
            Assert.Equal("EDS", y(0))
        End Sub

【问题讨论】:

  • 我在 VB.NET tuple documentation page 上提交了一个GitHub issue
  • 为了做一个清晰和未来可维护的工作,我认为你必须使用Structure而不是ValueTuple。然后你可以声明一个 Dictionary(Of String, YourStructure)。之后,您不会遇到后期绑定问题,因为 LINQ 查询下的命名类型也会被继承。
  • @G3nt_M3caj 元组名称不传播到哪里?编译:LexerEnglishFullWithTuple.Values.Select(Function(x) $"{x.Id}, {x.IdString}, {x.Arity}").
  • @ZevSpitz 是的,毫无疑问。但是方法与我的评论有关。在我的情况下,我永远不会声明带有内联 ValueTuple 的字典。 Structure 在我看来,作为 ValueTuple 的替代方案,它是命名类型的更紧凑和更好的方法。这么说的。这只是我的“作案手法”,考虑到 ValueTuple 仅限于 .NET 的某个较高版本并导入一些 Nuget 包,我认为这不是一个坏建议。
  • 文档has been updated;并且可以看到here

标签: vb.net dictionary tuples


【解决方案1】:

试试这个:

Dim LexerEnglishFullWithTuple As New Dictionary(Of String, (Id As Integer, IdString As String, Arity As Integer)) From {
    {"LET", (1, "000000001", 0)},
    {"PUT", (2, "000000002", 2)}
}

For Each x In LexerEnglishFullWithTuple
    Dim value = x.Value
    Console.WriteLine(value.Id)
    Console.WriteLine(value.IdString)
    Console.WriteLine(value.Arity)
Next

【讨论】:

    【解决方案2】:

    您只需像其他任何方式一样声明元组属性的名称和类型:

    Public Shared LexerEnglishFullWithTuple As New Dictionary(Of String, (Id As Integer, IdString As String, Arity As Integer)) From {
        {"LET", (1, "000000001", 0)},
        {"PUT", (2, "000000002", 2)},
        '...
    

    【讨论】:

      猜你喜欢
      • 2017-10-01
      • 2011-07-12
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      • 2019-02-12
      • 2019-10-25
      • 2020-09-25
      • 1970-01-01
      相关资源
      最近更新 更多