【问题标题】:Declaring Dictionary(Of Integer, AnonymousType) in vb.net在 vb.net 中声明 Dictionary(Of Integer, AnonymousType)
【发布时间】:2017-04-04 11:18:56
【问题描述】:

我想声明一个 vb.net 字典,其中一个整数作为键,一个匿名对象作为值。这由每个循环的并行填充。匿名类的属性总是相同的。但是有没有办法用匿名对象的签名来声明字典呢?

现在,我正在使用整数和对象的字典。

Dim MyDict As New Dictionary(Of String, Dictionary(Of Integer, Object))(12)
'In my loop
Dim MyLinqDict = Something.GroupBy(…).ToDictionary(Function(x) x.Kex, Function(x) New With {.a = 1, .b = 2})
MyDict.Add(MyKey, MyLinqDict)

现在,显而易见的问题是,内部字典的内容只是一个对象。我不知道,如果,如果是,我怎么能用实际的对象声明那个内部字典。我也不知道是否可以将该“对象”类型转换为匿名类型。

Dim MyContent = DirectCast(MyDict("Some key")(1), ???).a

有人可以在这方面帮助我吗?

【问题讨论】:

  • 你不能同时拥有它。匿名与否。如果您需要能够转换并明确访问属性a,那么您需要定义它而不是使用对象。如果你希望它匿名,你必须相信你不会得到任何没有 a 的对象
  • 匿名类型是 Linq 的一种便利。当您必须这样做时,它们不再方便。所以不要这样做,声明一个小助手类来存储结果。现在很简单。

标签: vb.net dictionary anonymous-types


【解决方案1】:

如果如你所说,属性总是相同的,只需创建一个新类并填充它:

Dim MyDict As New Dictionary(Of String, Dictionary(Of Integer, MyObject))(12)

Dim MyLinqDict = Something.GroupBy(…).ToDictionary(Function(x) x.Kex, Function(x) New MyObject With {.a = 1, .b = 2})

Public Class MyObject
    Public Property a() As Integer
    Public Property b() As Integer
End Class

问题解决了!

【讨论】:

  • 谢谢!这就是解决方案。
【解决方案2】:

没有。类型未知,因为它是..匿名的。

如果所有值的项数相同,则可以使用 Tuple:

Dim d1 = New Dictionary(Of Integer, Dictionary(Of Integer, Tuple(Of Integer, Integer)))

Dim d2 = {1, 2}.ToDictionary(Function(i) i, Function(i) Tuple.Create(1, 2))

d1.Add(0, d2)

Dim MyContent = d1(0)(1).Item1

【讨论】:

    【解决方案3】:

    创建一个简单的 POCO 类。这确实是最好的解决方案。

    假设地说,如果您创建一些通用辅助方法,您可以使用具有通用类型推断的匿名类。

    static Dictionary<TKey, TValue> Create<TKey, TValue>(TKey sampleKey, TValue sampleValue)
    {
        return new Dictionary<TKey, TValue>();
    }
    
    static TValue GetValueForKey<TKey, TValue>(IDictionary<TKey, TValue> dic, TKey key)
    {
        return dic[key];
    }
    
    // Usage
    var anonymousObject = new { a = "a_ok", b = "b_ok" };
    var dic = Create(0, anonymousObject);   // Only creates the dictionary
    dic.Add(1, anonymousObject);            // Adds a key/value pair
    
    var value = GetValueForKey(dic, 1).a;   // Yields "a_ok"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-06
      • 1970-01-01
      • 2015-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多