Is there a way to store a delegate without binding it to an object like how you can with a MethodInfo? Right now I am storing a MethodInfo so I can give it the object to cal
What you want is called an open instance delegate. It isn't supported directly in the C# language, but the CLR supports it.
Basically, an open instance delegate is the same as a normal delegate, but it takes an extra parameter for this
before the normal parameters, and has a null target (like a delegate for a static method). For instance, the open instance equivalent of Action
would be:
delegate void OpenAction(TThis @this, T arg);
Here's a complete example:
void Main()
{
MethodInfo sayHelloMethod = typeof(Person).GetMethod("SayHello");
OpenAction action =
(OpenAction)
Delegate.CreateDelegate(
typeof(OpenAction),
null,
sayHelloMethod);
Person joe = new Person { Name = "Joe" };
action(joe, "Jack"); // Prints "Hello Jack, my name is Joe"
}
delegate void OpenAction(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);
}
}
Have a look at this article for more details.