简体   繁体   English

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

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

As we know, by reflection we can create an class instance, but the type is object. 众所周知,通过反射我们可以创建一个类实例,但是类型是对象。 Here are some sample code. 这是一些示例代码。

  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<? ,?>;

The SerializableDictionary is a subclass of Dictionary. SerializableDictionary是Dictionary的子类。 Why will I have to cast this object? 为什么我必须投射此对象? Because I want to add some elements into the SerilaizbleDictionary. 因为我想在SerilaizbleDictionary中添加一些元素。 The elements are from another dictioanry. 这些要素来自另一种专制。

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

How can I do this? 我怎样才能做到这一点? Thank you very much. 非常感谢你。

If the items are coming from another Dictionary then could you not simply write a generic method and let it handle the generic typing? 如果这些项来自另一个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;
}

As mentioned in the comments consider casting to the IDictionary interface. 如评论中所述,考虑转换为IDictionary接口。 Specifically the IDictionary.Add method. 特别是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);
}

For example: 例如:

// 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);
}

Make sure that the types match between dictionary and stronglyTypedDictionary . 确保dictionarystronglyTypedDictionary之间的类型匹配。

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

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