Is there a way to pass a method as a parameter without knowing anything about the method in advance?
Can Func<input, return>
be called without knowing the method's parameter/return type?
Is there a way to pass a method as a parameter without knowing anything about the method in advance?
Can Func<input, return>
be called without knowing the method's parameter/return type?
The closest you can come is to use Delegate
- the caller will need to pick the right delegate type. That's exactly why Control.Invoke
uses Delegate
instead of a specific delegate type.
Alternatively, there's MethodInfo
as HackedByChinese suggests. Which one you should use depends on what you're trying to achieve - each is useful in different contexts. If you're trying to describe a method, then MethodInfo
is probably the best approach. If you're trying to represent a callable action of some kind (which can take parameters and have a return value) then a delegate is probably more useful.
If you tell us more about what you're trying to achieve, we may be able to help you more.
It sounds that invoking a method via reflection would be what you're interested in.
See MethodInfo.
Seems that you could be overengineering here.. You should properly look at the surrounding infrastructur in you code, and try to refactor that instead.
But if you really need to, you can do it with generics. Now, I would not recommend this - but this function you could call with anything, you would have to define Y and T and call time.
public virtual Y MyWrapperFunction<T,Y>(Func<T,Y> func, T param)
{
return func(param);
}
But be warned - generics can give you all sorts of different problems ;)