mercredi 30 novembre 2016

How can I get the return type of a Func

I have the following type hierarchy:

public abstract class Controller {}
public sealed class PersonController : Controller {}
public sealed class OrderController : Controller {}

I also have a method that resolves the instance of a given type on demand (think of it as a layman's IOC):

private void Resolve<T>(Func<T>[] controllerFactories) where T : Controller
{
    Array.ForEach(controllerFactories, x => 
    {
        // This returns Controller instead of the child class
        Console.WriteLine(x.Method.ReturnType);
        var controllerInstance = x();
    });
}

I need to figure out the type of T in Func<T> but when I try:

void Main()
{
    var factories = new Func<Controller>[] {
        () => new PersonController(),
        () => new OrderController()
    };

    Resolve(factories);
}

I get Controller instead of the PersonController and OrderController.

Any ideas?





Aucun commentaire:

Enregistrer un commentaire