Pass a variable ViewModel type as generic to a method

DontVoteMeDown

I have a method that works with generic:

public static IRestResponse<T> Get<T>(long id, string apiEndPoint) where T : new()
{
        return Execute<T>(Method.GET, null, string.Concat(apiEndPoint, "/", id));
}

I use this method passing a view model as generic to get the parsed result:

var result = RestHelper.Get<AnyViewModel>(1, "Country"));

But I came to a case that I have a variable entity where I get the view model from:

var entity = "Country"; // This comes as a parameter
var viewModels = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(x => x.FullName.Contains("Core.ViewModel"));

if (viewModels != null)
{
    Type viewModel = viewModels.GetTypes().FirstOrDefault(x => x.Name.Contains(entity));

    if (viewModel != null)
    {
        var result = RestHelper.Get<???>(1, entity);
    }
}

So I can get the view model type with reflection but I don't know what to pass to the <???> generic of the function.

UPDATE

I don't know how much this influences the reflection, but I have more overloads of the Get method:

public static IRestResponse Get(string apiEndPoint)
public static IRestResponse<T> Get<T>(string apiEndPoint) where T : new()
public static IRestResponse Get(long id, string apiEndPoint)
public static IRestResponse<T> Get<T>(long id, string apiEndPoint) where T : new()
McGarnagle

You'll have to use reflection to call the Get<T> method with the generic parameter, using MakeGenericMethod.

Edit Since there are multiple overloads, use GetMethods instead and narrow it down to the one you're looking for. (I don't see an overload of GetMethod that lets you specify the type arguments.)

MethodInfo method = typeof(RestHelper).GetMethods(BindingFlags.Static | BindingFlags.Public)
    .Where(method => method.Name == "Get" 
        && m.GetGenericArguments().Length == 1
        && m.GetParameters().Length == 2
        // just to be certain, in case someone adds more overloads in the future ...
        && m.GetParameters()[0].ParameterType == typeof(int)
        && m.GetParameters()[1].ParameterType == typeof(string))
    .FirstOrDefault();
if (method == null)
    throw new InvalidOperationException("Couldn't find an overload of RestHelper.Get<T> with int, string parameters");
MethodInfo genericMethod = method.MakeGenericMethod(viewModel);
genericMethod.Invoke(null, new object[] { 1, entity });

Edit

To use "List<viewModel>", you can use Type.MakeGenericType to get the List<T>:

var genericType = typeof(List<>).MakeGenericType(viewModel);
var genericMethod = method.MakeGenericMethod(genericType);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related