dimanche 23 octobre 2016

Cast Generic Object with getting type from Reflection

I'm trying to cast an object in a generic object where i need to change the type dynamically

Dog<T> inherit Animal class "T" must inherit from EntityBase For Example Chihuahua inherit EntityBase

for (int i = 0; i < list.Count(); i++){
if (list?.ElementAt(i)?.GetType().GetTypeInfo().BaseType == typeof(Animal))
{
var type = list.ElementAt(i).GetType();
// is wrong, must use a class no a type
//var animal = list.ElementAt(i) as GenericObject< Dog<type >> 
//Correct syntax but cast results null
var animal = list.ElementAt(i) as GenericObject< Dog<EntityBase>> 
//animal is null
DoStuff(animal);
}

If I use the next code works

if (list?.ElementAt(i)?.GetType() == typeof(Dog<Chihuahua>))
   {   
   DoStuff(list.ElementAt(i) as Dog<Chihuahua>);
   }

I want to do it most generic possible, thanks a lot!

I will share the project i'm doing when finish!





Aucun commentaire:

Enregistrer un commentaire