lundi 31 août 2015

Is it possible to cast to a type using type name in a string variable? [duplicate]

This question already has an answer here:

Is it possible to build a type name and recast an object to a specific type? The target types will be contained in the same assembly, and there will be hundreds. Example code:

var isPropertyInfo = objCollection as PropertyInfo;
if (isPropertyInfo != null)
{
    var propType = ((PropertyInfo)objCollection).PropertyType;
    var containerType = StripContainerType(propType.FullName);
    var itemType = StripItemType(propType.FullName);
    var fullTypeName = containerType + "<" + itemType + ">";
        // ex:  "System.Collections.Generic.ICollection<Customer>"
    var fullType = Type.GetType(itemType);
    dynamic coll;
    // now I want to do something *LIKE* (pseudocode-ish)
    // coll = objCollection as fullType;

Do not consider the last line as valid code. It's just where I'm stuck.





Aucun commentaire:

Enregistrer un commentaire