C# delegate not bound to an instance?

后端 未结 4 1969
盖世英雄少女心
盖世英雄少女心 2021-01-04 08:47

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

4条回答
  •  独厮守ぢ
    2021-01-04 09:08

    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.

提交回复
热议问题