Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I started it out optimistic, but it turned out really ugly.</p> <p>I'll post it anyways since it does the job after all.</p> <p>You can easily add Func constructors to support Action and lose the VoidReturn hack.</p> <pre><code>public class Func { public readonly MethodInfo Method; public readonly object Target; #region Ctors public static Func Get&lt;TResult&gt;(Func&lt;TResult&gt; func) { return new Func(func.Method, func.Target); } public static Func Get&lt;T, TResult&gt;(Func&lt;T, TResult&gt; func) { return new Func(func.Method, func.Target); } public static Func Get&lt;T1, T2, TResult&gt;(Func&lt;T1, T2, TResult&gt; func) { return new Func(func.Method, func.Target); } public static Func Get&lt;T1, T2, T3, TResult&gt;(Func&lt;T1, T2, T3, TResult&gt; func) { return new Func(func.Method, func.Target); } #endregion private Func(MethodInfo method, object target) { this.Method = method; this.Target = target; } public object Run(params object[] parameters) { return this.Method.Invoke(this.Target, parameters); } } public class MyClass { public string Data { get; set; } public int Add(int x, int y) { return x + y; } public bool IsZero(int i) { return i == 0; } public void Print(object msg) { Console.WriteLine(msg); } public bool ValidateData() { return string.IsNullOrEmpty(this.Data); } public void TestMethods() { var tests = new Dictionary&lt;Func, object[][]&gt; { { Func.Get&lt;int, int, int&gt;(this.Add), new[] { new object[] {2, 3}, new object[] {5, 0}, new object[] {10, -2} } }, { Func.Get&lt;int, bool&gt;(this.IsZero), new[] { new object[] {1}, new object[] {0}, new object[] {-1} } }, { Func.Get&lt;object, VoidReturn&gt;(o =&gt; { this.Print(o); return VoidReturn.Blank; }), new[] { new object[] {"Msg1"}, new object[] {"Msg2"}, new object[] {"Msg3"} } }, {Func.Get(this.ValidateData), null} }; foreach (var testFunc in tests) { Console.WriteLine("Testing method: " + testFunc.Key.Method.Name); Console.WriteLine(); foreach (var parameters in testFunc.Value) { Console.WriteLine("Parameters: " + string.Join(", ", parameters)); var result = testFunc.Key.Run(parameters); Console.WriteLine(result is VoidReturn ? "*void" : ("Returned: " + result)); Console.WriteLine(); } Console.WriteLine("________________________________"); Console.WriteLine(); } } private enum VoidReturn { Blank } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload