vendredi 28 avril 2017

Get the type of a closed type from the static constructor of the generic class that the closed type derives from

If I have a generic type with a static constructor and a constrain

interface IMyInterface
{
...
}

class MyGeneric<T> where T : IMyInterface
{
    static MyGeneric()
    {
    ....
    }
}

And a closed type:

class MyClass : MyGeneric<TypeImplementingIMyInterface>
{
    ...
}

Is it possible, through reflection, to retrieve the type of the closed type (MyClass) from within the static constructor in the MyGeneric? If so, how?

I have tried so far without success:

  • var t = typeof(MyGeneric<>);
  • var t = MethodBase.GetCurrentMethod().GetType();

I know I can use the Curiously Recurring Template Pattern to do what I want:

interface IMyInterface
{
}

class MyBase
{

}

class MyGeneric<T1, T2> : MyBase where T1 : IMyInterface, T2 : MyBase
{
    static MyGeneric()
    {
        var t = typeof(T2);
        // ...
    }
}

class MyClass : MyGeneric<TypeImplementingIMyInterface, MyClass>
{
    // ...
}

I would like to know if there is another approach that can be used in the described scenario.

I accept a No as an answer if that is the answer.





Aucun commentaire:

Enregistrer un commentaire