How to get generic type arguments of a generic type from a derived type in C #

Let's say I have:

class MyBase<T1, T2>{}

class MyConcreteBase<T2> : MyBase<ConcreteType1, T2>{}

class MyConcrete1 : MyConcreteBase<ConcreteType2>{}

class MyConcrete2 : MyBase<ConcreteType1, ConcreteType2>{}

How to get types T1and T2if I have an instance of MyConcrete1or MyConcrete2or MyConcreteBaseor any other type instance derived fromMyBase<T1, T2>

Now, when I do this, I get up on the inheritance chain using .GetType().BaseTypewhile BaseType.Name.StartsWith("MyBase"), and then using.GetGenericArguments()

It works, but I am not satisfied with this, especially the .StartsWith("MyBase")part.

Anyone have any other suggestions?

+5
source share
6 answers

, . BaseType.IsAssignableFrom(typeof(MyBase<,>)) (, BaseType MyBase<,> - ).

, :

public Type T1_Type { get { return typeof(T1); } }
public Type T2_Type { get { return typeof(T2); } }

, ? .

EDIT: , IsAssignableFrom, . : , -

+2

GenericType, BaseType<,>. :

var type = c.GetType();
Type baseType = type;
while(null != (baseType = baseType.BaseType)) 
{
    if (baseType.IsGenericType) 
    {
        var generic = baseType.GetGenericTypeDefinition();
        if (generic == typeof(MyBase<,>)) 
        {
            var genericTypes = baseType.GetGenericArguments();
            // genericTypes has the type argument used to construct baseType.
            break;
        }
    }
}   
+3

, , . , , : , BaseType null. , , , GetGenericArguments. LINQ.

0

, :

class MyBase<T1, T2> {
    protected Type GetT1() { return typeof(T1); }
    protected Type GetT2() { return typeof(T2); }
}
0

, (, ) :

public Type[] BaseGenericTypes<T>(T instance)
    {
        Type instanceType = instance.GetType();

        Type objectType = new object().GetType();

        while (instanceType.BaseType != objectType)
        {
            instanceType = instanceType.BaseType;
        }
        return instanceType.GetGenericArguments();
    }

- .

0
-1
source

All Articles