C # delegate not associated with instance?

Is there a way to save a delegate without tying it to an object, as you can with MethodInfo? Right now I am storing MethodInfo, so I can give it an object to call the for method. But I prefer it to be a delegate. Like the attribute that tells .net that the first parameter is "this"?

MethodInfo mi; Action<string> func; mi.Invoke(this,new object[]{str}); func(this, str); //Is this possible with a delegate? 
+8
c #
source share
4 answers

What you want is called open instance delegate . It is not directly supported in C #, but the CLR supports it.

In principle, an open instance delegate is the same as a normal delegate, but before normal parameters it takes an additional parameter for this and has a zero target (for example, a delegate for a static method). For example, the open equivalent of an instance of Action<T> would be:

 delegate void OpenAction<TThis, T>(TThis @this, T arg); 

Here is a complete example:

 void Main() { MethodInfo sayHelloMethod = typeof(Person).GetMethod("SayHello"); OpenAction<Person, string> action = (OpenAction<Person, string>) Delegate.CreateDelegate( typeof(OpenAction<Person, string>), null, sayHelloMethod); Person joe = new Person { Name = "Joe" }; action(joe, "Jack"); // Prints "Hello Jack, my name is Joe" } delegate void OpenAction<TThis, T>(TThis @this, T arg); class Person { public string Name { get; set; } public void SayHello(string name) { Console.WriteLine ("Hi {0}, my name is {1}", name, this.Name); } } 

See this article for more details.

+11
source share

You can use the Delegate.CreateDelegate method to create a strongly typed delegate for MethodInfo .

If you don’t know the method signature at compile time, you can either create Func<...> using Reflection, or create a lambda expression that calls MethodInfo :

 MethodInfo methodInfo = ...; object thisObj = ...; Func<object[]> callMethod = args => methodInfo.Invoke(thisObj, args); 

(This is called currying)

Note that this will still reflect performance on reflection every time the delegate is called, unlike Delegate.CreateDelegate .

+5
source share

A delegate is just a MethodInfo (actually, a MethodBase ) and an object reference, with some internal pointers to performance. Therefore, if you have MethodInfo , you essentially have an unrelated delegate. What is your specific use case?

0
source share

Why not just

 Action<T, string> unbound = (This, str) => This.Method(str); 

so you can

 unbound(instanceA, "hello"); unbound(instanceB, "world"); 

or even

 Action<string> bound = str => unbound(instanceC, str); 
0
source share

All Articles