繁体   English   中英

如何将对象转换为未知的类类型?

[英]How can I cast an object to some unknown class type?

众所周知,通过反射我们可以创建一个类实例,但是类型是对象。 这是一些示例代码。

  Type type = p.GetType();
  Type keyType = type.GetGenericArguments()[0];
  Type valueType = type.GetGenericArguments()[1];

   var r = Activator.CreateInstance(typeof(SerializableDictionary<,>)
                .MakeGenericType(new Type[] { keyType, valueType })) 
                   as SerializableDictionary<? ,?>;

SerializableDictionary是Dictionary的子类。 为什么我必须投射此对象? 因为我想在SerilaizbleDictionary中添加一些元素。 这些要素来自另一种专制。

foreach (KeyValuePair<?, ?> kvp in d)// d is another dictionary
{
   r.Add(kvp.Key, kvp.Value);
}

我怎样才能做到这一点? 非常感谢你。

如果这些项来自另一个Dictionary那么您是否不能简单地编写泛型方法并让其处理泛型类型?

private SerializableDictionary<TKey, TValue> ToSerializable<TKey, TValue>(Dictionary<TKey, TValue> source)
{
    var output = new SerializableDictionary<TKey, TValue>();

    foreach (var key in source.Keys)
    {
        output.Add(key, source[key]);
    }

    return output;
}

如评论中所述,考虑转换为IDictionary接口。 特别是IDictionary.Add方法。

Type type = p.GetType();
Type keyType = type.GetGenericArguments()[0];
Type valueType = type.GetGenericArguments()[1];

var dictionary =
    (IDictionary) Activator
        .CreateInstance(typeof(SerializableDictionary<,>)
        .MakeGenericType(new Type[] { keyType, valueType }));

foreach(var item in stronglyTypedDictionary)
{
    dictionary.Add(item.Key, item.Value);
}

例如:

// Assume dictionary is created using reflection
IDictionary dictionary = new Dictionary<string, object>();
var stronglyTypedDictionary = new Dictionary<string, object> { {"hello", null} };

foreach(var item in stronglyTypedDictionary)
{
    dictionary.Add(item.Key, item.Value);
}

确保dictionarystronglyTypedDictionary之间的类型匹配。

暂无
暂无

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

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