Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the Type of a generic Interface?

Tags:

c#

generics

I got a generic Interface like this :

public interface IResourceDataType<T>
{
    void SetResourceValue(T resValue);
}

Then I got this class that implements my Interface :

public class MyFont : IResourceDataType<System.Drawing.Font>
{
    //Ctor + SetResourceValue + ...
}

And finally I got a :

var MyType = typeof(MyFont);

I, now, want to get the System.Drawing.Font Type from MyType ! At the moment, I got this code :

if (typeof(IResourceDataType).IsAssignableFrom(MyType))
{
    //If test is OK
}

But I don't manage to "extract" my Type here... I tried a couple of things with GetGenericArguments() and other things but they either don't compile or return a null value/List... What do I have to do ?

EDIT : Here is the solution that fit my code for those who will get the same problem :

if (typeof(IResourceDataType).IsAssignableFrom(MyType))
{
    foreach (Type type in MyType.GetInterfaces())
    {
        if (type.IsGenericType)
            Type genericType = type.GetGenericArguments()[0];
        }
    }
}
like image 723
Guillaume Slashy Avatar asked Jan 16 '12 14:01

Guillaume Slashy


People also ask

Can a generic type be an interface?

Java Generic Classes and SubtypingWe can subtype a generic class or interface by extending or implementing it. The relationship between the type parameters of one class or interface and the type parameters of another are determined by the extends and implements clauses.

How do I get a class instance of generic type T?

The short answer is, that there is no way to find out the runtime type of generic type parameters in Java. A solution to this is to pass the Class of the type parameter into the constructor of the generic type, e.g.

What is type as generic in Java?

Generic types and methods are the defining new feature of Java 5.0. A generic type is defined using one or more type variables and has one or more methods that use a type variable as a placeholder for an argument or return type. For example, the type java. util.


1 Answers

Since your MyFont class only implements one interface, you can write:

Type myType = typeof(MyFont).GetInterfaces()[0].GetGenericArguments()[0];

If your class implements several interfaces, you can call the GetInterface() method with the mangled name of the interface you're looking for:

Type myType = typeof(MyFont).GetInterface("IResourceDataType`1")
                            .GetGenericArguments()[0];
like image 111
Frédéric Hamidi Avatar answered Sep 20 '22 11:09

Frédéric Hamidi