简体   繁体   中英

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

You want to use the MakeGenericMethod method that is available on MethodInfo, eg

    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 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM