none
How to call Class.Method<T> when I know type of T ? RRS feed

  • Question

  • Hi all!

    I have web-service accepting as parameter a type of anonymous delegate represented by string (Type.GetType().AssemblyQualifiedName).
    This type parsed quite well (Type.GetType(string)).
    Now I need to execute some generic method, which accepts this delegate and returns some generic type with the same delegate type:
    SomeObject<TDelegate> obj = Class.Method<TDelegate>() 

    Can I call my method if I know only the type of this delegate ? 


    Friday, September 4, 2009 7:10 AM

Answers

  • Hello,

    Sample is here:
    http://blogs.microsoft.co.il/blogs/bursteg/archive/2006/11/15/InvokeStaticGenericMethod.aspx
    Vitaliy Liptchinsky http://dotnetframeworkplanet.blogspot.com/
    Friday, September 4, 2009 7:24 AM
  • Yes, but you have to keep using Reflection. Roughly something like this

    yourType.GetMethod("Method").MakeGenericMethod(typeof(TDelegate)).Invoke(...)



    Mattias, C# MVP
    • Marked as answer by eryang Friday, October 9, 2009 3:04 AM
    Friday, September 4, 2009 7:28 AM
    Moderator

All replies

  • Hello,

    Sample is here:
    http://blogs.microsoft.co.il/blogs/bursteg/archive/2006/11/15/InvokeStaticGenericMethod.aspx
    Vitaliy Liptchinsky http://dotnetframeworkplanet.blogspot.com/
    Friday, September 4, 2009 7:24 AM
  • Yes, but you have to keep using Reflection. Roughly something like this

    yourType.GetMethod("Method").MakeGenericMethod(typeof(TDelegate)).Invoke(...)



    Mattias, C# MVP
    • Marked as answer by eryang Friday, October 9, 2009 3:04 AM
    Friday, September 4, 2009 7:28 AM
    Moderator
  • Thanks, Vitaliy!

    Friday, September 4, 2009 8:12 AM
  • Now next question.

    I'm working with EntityModel (MyEntities) and I have now:

    expressionT {(x, y) => x.Status.Where(z => (z.Status_ID > y))} object {System.Linq.Expressions.Expression<System.Func<MyEntities,int,object>>}
    Func<MyEntities,int,object> is my delegate here;

    But, I cant cast 'expressionT' to this type.

    I need it for next reason: I have to set exact parameters for this expression/delegate and not like an array.

    delegate.Invoke(object obj, object[] args) accepts an array of parameters
    When I calling Invoke method of generated delegate (as object) 

    object[] args = Getsomeargs();
    MethodInfo miDelegate = typeofDelegate.GetMethod("Invoke");
    var result = miDelegate.Invoke(compiled,  args)

    Lambda expression z.Status_ID > y comes to be like this: z.Status_ID > Convert(((object[])args)[0]), Int32)
    (sorry cant find now exact syntax but pay attention to object[] and indexing - [0])

    And then, when I'm trying to execute result ObjectQuery<Status> throws an error that 'ArrayIndex is not supported in Linq to entities'...

    So, how can I set parameters for my delegate, avoiding arrays? 
    Friday, September 4, 2009 11:19 AM