unos baghaii
unos baghaii

Reputation: 77

Call generic method which T is a Type

there is a generic method which selects a field from an entity as below

public object GetOrderDynamically<T>(Expression selectPredicate, Expression predicate, Type type)
    {
        var order = orderFacade.FetchMulti((Expression<Func<Order, bool>>) predicate).AsQueryable();
        return order.Select((Expression<Func<Order, T>>)selectPredicate).FirstOrDefault();

    }

Search result for calling the method was this

the problem : I want to clarify type of the selected field . but this method is located in business layer and I can use it with its interface . actually business layers classes would be injectd into my class with IoC .

Somehow I want to call my methods with reflection which are instantiated by injection and be able to set T as a Type

Any help . thanks

Upvotes: 1

Views: 127

Answers (1)

James Simpson
James Simpson

Reputation: 1150

You want to use the MakeGenericMethod method that is available on MethodInfo, e.g

    someTarget.GetType()
        .GetMethod("SomeGenericMethod")
        .MakeGenericMethod(typeof(SomeGenericArgument)
        .Invoke(someTarget, someParameters);

See also:

Calling generic method with a type argument known only at execution time

EDIT - For given example

orderBiz.GetOrderDynamically<tt>(selectExp, predicateExp); – unos baghaii 5 mins ago

    orderBiz.GetType().GetMethod("GetOrderDynamically").MakeGenericMethod(tt).Invoke(orderBiz, new object [] { selectExp, predicateExp });

Upvotes: 2

Related Questions