Calling a generic method in a loop with different types known at compile time

Consider the method in the interface:

public Interface IA {
    T[] Get<T>() where T : IB;
}

Elsewhere, I would call this method n times for n types that are known at compile time. The following code illustrates my intent.

foreach(Type t in new Type[] { typeof(X), typeof(Y), typeof(Z) }) 
{
    InterfaceXYZImplement[] arr = c.Resolve<IA>().Get<t>();
    //...more here
}

Now the loop foreachobviously makes the type become runtime, so I would have to use it MakeGenericMethod.

Is there a way to write the code so that I can execute the code for X, Yand Z, but call the method written only once?

Wrapping the code in the method will only move the problem up (which is a partial solution, but not the final one, heh).

+3
source share
2 answers

, dynamic .NET4.

, DLR , , , , dynamic. :

IB[] Get(IA a, Type t)
{
    dynamic dummy = Activator.CreateInstance(t);
    return Get(a, dummy);
}

T[] Get<T>(IA a, T dummy) where T : IB
{
    return a.Get<T>();
}

:

foreach(var t in new Type[] { typeof(X), typeof(Y), typeof(Z) })
{
    IB[] arr = Get(c.Resolve<IA>(), t);
    // do more stuff here
}

, :

  • Activator.CreateInstance(t). , , .
  • - IB, . .
  • IB, .
+2

:

public static class Extensions
{
    public static void Get<T>(this IA a, Action<T[]> action, params Type[] types) where T : IB
    {
        foreach (var type in types)
        {
            var method = a.GetType().GetMethod("Get").MakeGenericMethod(type);
            var ts = (T[])method.Invoke(a, null);
            action(ts);
        }
    }
}

:

a.Get(arr => { 
   // work on result
}, typeof(X), typeof(Y), typeof(Z));
+1

All Articles