vendredi 12 juillet 2019

Using reflection to cast unknown object to generic class

I have a method which takes an object as a parameter. Within that method I walk through that objects properties with reflection. Some properties are of a generic class type. I like to read a property of that generic class property, but I cannot cast it to a generic class.

public abstract class BaseClass
{
    public int Id { get; set; }
}

public abstract class GenericClass<T>: BaseClass
{
    public string Description { get; set; }
}

public class DerivedClassA: GenericClass<DerivedClassA>
{
    public string A { get; set; }
}

public class DerivedClassB: GenericClass<DerivedClassB>
{
    public string B { get; set; }
}

public class ReflectingClass: BaseClass
{
    public string Code { get; set; }
    public DerivedClassA DerA { get; set; }
    public DerivedClassB DerB { get; set; }
}

public static void Reflecting(object obj)
{
    var t = GetType(obj)
    foreach (var pi in t.GetProperties())
    {
        if (obj.GetType().BaseType.GetGenericTypeDefinition() == typeof(GenericClass<>)
        {
            var genClassObjProperty = ((GenericClass<T>)obj).Description; // Error, cannot do this at all !!!
        }
    }
}

What I want is for the code to walk to the properties and whatever the derived class actually is get the Description property of the GenericClass it is derived from.

I am using a generic class, because elsewhere in the code I call methods by their derived class and get the proper class type without resorting to all kinds of cast and passing types. I.e:

DerivedClassA.DoSomething() 

instead of

BaseClass.DoSomething<DerivedClassA>()

or

BaseClass.DoSomething(type derivedClassType)





Aucun commentaire:

Enregistrer un commentaire