KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
Mostly it comes handy that C# delegates already store the object together with the member function. But is there a way, to store -- and pass as parameters -- only the member function itself, just as the good old pointer-to-member-function in C++? In case the description is less than clear, I give a self-contained example. And, yes, in the example the insistence to pass around member functions is totally pointless, but I have more serious uses for this. class Foo { public int i { get; set; } /* Can this be done? public static int Apply (Foo obj, ???? method, int j) { return obj.method (j); } */ public static int ApplyHack (Foo obj, Func<int, int> method, int j) { return (int) method.Method.Invoke (obj, new object [] { j }); } public static readonly Foo _ = new Foo (); // dummy object for ApplyHack public int Multiply (int j) { return i * j; } public int Add (int j) { return i + j; } } class Program { static void Main (string [] args) { var foo = new Foo { i = 7 }; Console.Write ("{0}\n", Foo.ApplyHack (foo, Foo._.Multiply, 5)); Console.Write ("{0}\n", Foo.ApplyHack (foo, Foo._.Add, 5)); Console.ReadKey (); } } You see, the only workaround I've found is rather ugly and probably slow.
Tags (comma-separated)
Save Edits
Cancel