I've noticed that the Delegate class has a Target property, that (presumably) returns the instance the delegate method will execute on. I want to do something like this:
void PossiblyExecuteDelegate(Action<int> method)
{
if (method.Target == null)
{
// delegate instance target is null
// do something
}
else
{
method(10);
// do something else
}
}
When calling it, I want to do something like:
class A
{
void Method(int a) {}
static void Main(string[] args)
{
A a = null;
Action<int> action = a.Method;
PossiblyExecuteDelegate(action);
}
}
But I get an ArgumentException (Delegate to an instance method cannot have a null 'this') when I try to construct the delegate. Is what I want to do possible, and how can I do it?
In short after creating an immutable copy of an event delegate and checking it for null, it is completely safe to execute the copy.
A delegate is a type safe and object oriented object that can point to another method or multiple methods which can then be invoked later. It is a reference type variable that refers to methods.
Use the new keyword to instantiate a delegate. When creating a delegate, the argument passed to the new expression is written similar to a method call, but without the arguments to the method.
Definition and Usage delegateTarget property returns the element where the currently-called jQuery event handler was attached. This property is useful for delegated events attached by the on() method, where the event handler is attached at an ancestor of the element being processed.
Ahah! found it!
You can create an open instance delegate using a CreateDelegate overload, using a delegate with the implicit 'this' first argument explicitly specified:
delegate void OpenInstanceDelegate(A instance, int a);
class A
{
public void Method(int a) {}
static void Main(string[] args)
{
A a = null;
MethodInfo method = typeof(A).GetMethod("Method");
OpenInstanceDelegate action = (OpenInstanceDelegate)Delegate.CreateDelegate(typeof(OpenInstanceDelegate), a, method);
PossiblyExecuteDelegate(action);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With