Is it possible to use DLR to refer to a method in C #?
In dynamic languages ββlike JavaScript or Python, I could easily pass a method as an argument to another method. In C #, which is a statically typed language, I either use the Delegate type, which requires a lot of casting:
public static void AddMethod(Delegate del) {
and then use casting whenever I call this method
static void Main(string[] args) { AddMethod(new Func<object, bool>(Test)); } public static bool Test(object obj) { return true; }
Or I need to define dozens of overloads to satisfy any method calls:
public static void AddMethod<TResult>(Func<TResult> method) { } public static void AddMethod<T, TResult>(Func<T, TResult> method) { } public static void AddMethod<T1, T2, TResult>(Func<T1, T2, TResult> method) { } public static void AddMethod<T1, T2, T3, TResult>(Func<T1, T2, T3, TResult> method) { }
Is there a cleaner way to define an argument as a placeholder for all other methods? (I try to avoid MethodInfo or other Reflection things here)
I tried something like this:
public delegate dynamic DynamicDelegate(params dynamic[] args); public static void AddMethod(DynamicDelegate method) { }
But the compiler does not seem to accept a statically typed method for dynamically declared delegates!
Any other thoughts?