Lambda expression returned by delegate

Hi, I am trying to achieve something like this:

Method<TObjectType>(m=>m.GetData); //m is the instance of TObjectType 

if I can do this, then I can visit this expression and get the GetData method and use it to create a dynamic SQL query. I could do this by specifying the method name as a string, but I don't want to break the world with the strong type of my development friends.

I know that I have to give a precise definition of the delegate, but it still has not helped me;

 void Method<TObjectType>(Expression<Func<TObjectType, Delegate>> ex){/**/} 

Do you have an idea?

+6
source share
2 answers

Unfortunately, there is hardly such a thing as a “delegate”. For most purposes (and especially: to allow MethodInfo ), it should be a strongly typed delegate. This is due to the fact that GetData not a method, it is a group of methods. You really need to specify the method exactly or have a known delegate type (which ultimately does the same thing).

You have two practical options; work with object or add a shared one. For instance:

 void Method<TObjectType>(Expression<Func<TObjectType,object>> ex) {...} 

will work like:

 void Method<TObjectType, TValue>(Expression<Func<TObjectType,TValue>> ex) {...} 

The caller will use:

 Method<Foo>(x => x.GetData()); 

If you really want to use a delegate, the type should be predictable, for example:

 void Method<TObjectType>(Expression<Func<TObjectType,Func<int>>> ex) 

allows you to:

 Method<Foo>(x => x.GetData); 

Alternatively, if you know (for example) that the method is always without parameters, but you do not know the return type; maybe something like:

 void Method<TObjectType, TValue>(Expression<Func<TObjectType,Func<TValue>>> ex) 

which allows:

 Method<Foo, int>(x => x.GetData); 
+6
source

Are you looking for something like this?

 object InvokeMethod(Delegate method, params object[] args){ return method.DynamicInvoke(args); } int Add(int a, int b){ return a + b; } void Test(){ Console.WriteLine(InvokeMethod(new Func<int, int, int>(Add), 5, 4)); } 
0
source

Source: https://habr.com/ru/post/921741/