2010-06-17 4 views
7

Je souhaite effectuer un transtypage explicite à l'aide des informations de type d'un tableau à un autre lié par héritage. Mon problème est que lors de la diffusion à l'aide d'informations de type, le compilateur génère une erreur, mais mon exigence est de lancer dynamiquement en fonction des informations de type fournies.Coulée dynamique basée sur les informations de type

S'il vous plaît Aide

class Program 
{ 
    static void Main(string[] args) 
    { 
     Parent[] objParent; 
     Child[] objChild = new Child[] { new Child(), new Child() }; 
     Type TypParent = typeof(Parent); 

     //Works when i mention the class name 
     objParent = (Parent[])objChild; 

     //Doesn't work if I mention Type info 
     objParent = (TypParent[])objChild; 
    } 
} 

class Parent 
{ 
} 

class Child : Parent 
{ 
} 

Répondre

12

La seule façon que vous pouvez lancer dynamiquement avec la réflexion. Bien sûr, vous ne pouvez pas lancer objChild à TypParent[] - vous essayez de lancer un tableau de Child à un tableau de Type.

Vous pouvez utiliser la méthode .Cast<T>() appelée avec réflexion pour y parvenir:

MethodInfo castMethod = this.GetType().GetMethod("Cast").MakeGenericMethod(typeParent); 
object castedObject = castMethod.Invoke(null, new object[] { objChild }); 

Si vous en avez besoin pour les types non-IEnumerable, faire une méthode d'extension/statique:

public static T Cast<T>(this object o) 
{ 
    return (T)o; 
}