-1

I have created a FetchData method which returns IList<object> and it takes objectName(string) as parameter(name of the object of which we want to return List).

Task<IList<object>> FetchData(string processGuiId, string objectName);

I am calling a Gateway method from FetchData(string processGuiId, string objectName) to get data from source.

_gateway.ReadByQueryAsync<T>();

How can I get T from objectName for ReadByQueryAsync method?

d219
  • 2,707
  • 5
  • 31
  • 36

1 Answers1

0

You can't "create Generic T from objectName" but you can construct generic method from type.

I think you are looking for MethodInfo.MakeGenericMethod usage would be like this:

// somehow get fully qualified name from objectName
vat type = Type.GetType("fully qualified name"); 
var mi = _gateway.GetType().GetMethod("ReadByQueryAsync").MakeGenericMethod(type);

And call, for example:

mi.Invoke(_gateway, null)

or build a lambda with expression trees and cache it.

Example with Enumerable.First():

var mi = typeof(Enumerable)
    // cause multiple "First" methods
    .GetMethods()
    .Where(mi => mi.Name == "First" && mi.GetParameters().Length == 1)
    .First();
var type = Type.GetType("System.Int32");
var constructed = mi.MakeGenericMethod(type);
var obj = new[] { 1, 2 };
// you will have another order of parameters in Invoke if ReadByQueryAsync is instance method
var x = constructed.Invoke(
    null, // null cause First is extension method, should be obj if instance
    new[] { obj } // should be null for parameterless instance method
    ); // x = 1
Guru Stron
  • 102,774
  • 10
  • 95
  • 132