1

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

Community
  • 1
  • 1
unos baghaii
  • 77
  • 1
  • 9
  • 1
    It isn't clear what you want to obtain... Try writing how you call the method and how you would like to call the method. – xanatos Mar 16 '15 at 13:59
  • Are you asking how to call generic methods via reflection? It is a little unclear to me at present... – Chris Mar 16 '15 at 14:01
  • I want to call it like this var tt = typeof(Datetime); orderBiz.GetOrderDynamically(selectExp, predicateExp); – unos baghaii Mar 16 '15 at 14:12
  • It is simply not a good idea to mix generics and reflection. If the method takes a `Type`, it shouldn't also have a `` that means the same thing - and calling it via reflection isn't going to capitalise on the ``. You might as well just return `object` and forget the `` completely. – Marc Gravell Mar 16 '15 at 14:15

1 Answers1

2

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 });
Community
  • 1
  • 1
James Simpson
  • 1,150
  • 6
  • 11