繁体   English   中英

在不知道其类型的情况下获取字典键值对

[英]Get dictionary key-value pairs without knowing its type

我有一个对象instance

instance.GetType().GetGenericTypeDefinition() == typeof(Dictionary<,>)

是真的。 我的问题是,如何在不真正了解其泛型类型的情况下从该对象中提取键值对? 我想得到像KeyValuePair<object, object>[] 请注意,我也知道字典在运行时使用的泛型类型(但不是编译时)。 我认为需要某种反思?

后续:是否存在将object转换为SomeClass<>的一般机制(如果我知道这是正确的类型,当然)并因此使用它,因为类的实现不受通用类型的影响参数呢?

我会做Jeremy Todd说的话,除了可能会更短一些:

    foreach(var item in (dynamic)instance)
    {
       object key = item.Key;
       object val = item.Value;
    }

作为旁注(不确定是否有帮助),您可以获得这样的参数类型:

Type[] genericArguments = instance.GetType().GetGenericArguments();

要获得快速解决方案,您可以使用dynamic

Dictionary<string, int> myDictionary = new Dictionary<string, int>();

myDictionary.Add("First", 1);
myDictionary.Add("Second", 2);
myDictionary.Add("Third", 3);

dynamic dynamicDictionary = myDictionary;

foreach (var entry in dynamicDictionary)
{
  object key = entry.Key;
  object val = entry.Value;
  ...whatever...
}

这就是我想出来帮助我的原因。 它符合我当时的需求......也许它会帮助其他人。

foreach (var unknown in (dynamic)savedState)
{
  object dKey = unknown.Key;
  object dValue = unknown.Value;

  switch (dKey.GetType().ToString())
  {
    case "System.String":
      //Save the key
      sKey = (string)dKey;

      switch (dValue.GetType().ToString())
      {
        case "System.String":
          //Save the string value
          sValue = (string)dValue;

          break;
        case "System.Int32":
          //Save the int value
          sValue = ((int)dValue).ToString();

          break;
      }

      break;
  }

  //Show the keypair to the global dictionary
  MessageBox.Show("Key:" + sKey + " Value:" + sValue);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM