如何访问作为通用甚至动态类型传递的字典

本文关键字:动态 类型 字典 何访问 访问 | 更新日期: 2023-09-27 18:31:01

让我们有函数Process<T>(T data) .T可能是"任何"(表示支持)类型,例如。 int也作为Dictionary<U,V>,其中U,V是"任何"类型,等等。我们可以使用代码检测T是字典:

var type = typeof(T); // or data.GetType();
if (   (type.IsGenericType)
    && (type.GetGenericTypeDefinition() == typeof(Dictionary<,>)))
{
    var dict = data as Dictionary<,>; // FIXME: Make dictionary from data
    foreach (kv in dict)
    {
        ProcessKey(kv.Key  );
        ProcessVal(kv.Value);
    }
}

有没有办法将数据解释为字典,或者我们只需要单独的ProcessInt()ProcessDict<T>() where T: Dictionary<U, V>等?

第二个混淆层次:当函数的形式为 Process(dynamic data) 时,有什么方法可以访问其类型Dictionary<U, V>的数据(请注意 U、V 再次是"任何"支持的类型)?

如何访问作为通用甚至动态类型传递的字典

您可以使用动态:

  if ((type.IsGenericType) && (type.GetGenericTypeDefinition() == typeof(Dictionary<,>)))
            {
                var dict = data as IDictionary;
                foreach (dynamic entity in dict)
                {
                    object key = entity.Key;
                    object value = entity.Value;

                    ProcessKey(key);
                    ProcessVal(value);
                }
            }

这样,您可以拥有ProcessKeyProcessVal期望的对象。