I need to know if it's possible to access the underlying object that contains the method referenced by a delegate?
I know that the object is captured in the delegate because it is required when invoking the method.
A Delegate references it's target. Of course, static methods have no target, so a null check might be required.
class Program
{
static void Main(string[] args)
{
var container = new Container();
Func<string> doSomething = container.DoSomething;
Delegate d = doSomething;
// This will be the container, but you need to cast.
var c = (Container)d.Target;
Console.Read();
}
}
class Container
{
public string DoSomething()
{
return "";
}
}
I'm not sure what you are trying to achieve with this, but needing to know about the target type that is fulfilling a delegate reference might be a code smell or an indicator of a design issue.
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