开发者

Does C# support Bound Method or Method Closure (Special Closure which allows this to always point to instance)

Adobe has a very clear explanation here:

A bound method, sometimes called a method closure, is a method that is extracted from its instance. Examples of bound methods include methods that are passed as a开发者_StackOverflow中文版rguments to a function or returned as values from a function. A bound method is similar to a function closure in that it retains its lexical environment even when extracted from its instance. The key difference, however, between a bound method and a function closure is that the this reference for a bound method remains linked, or bound, to the instance that implements the method. In other words, the this reference in a bound method always points to the original object that implemented the method. For function closures, the this reference is generic, which means that it points to whatever object the function is associated with at the time it is invoked.

If C# support generic closure, is there a way to turn it into a more convenient Bound Method because it is really annoying and unatural not to be able to use this and artificially use sender instead and above all have to explicitely pass the sender object instead of being able to use the implicit this keyword.


Yes, given that definition, C# supports "bound methods".

class Greeter
{
   public string prefix { get; set; }

   public string greet(string who)
   {
      return prefix + " " + who;
   }
}

class Program
{
   public static void doit(Func<string, string> a)
   {
      Console.Out.WriteLine(a("World"));
   }

   static void Main(string[] args)
   {
      // pass doit a Greeter method bound to instance foo
      Greeter foo = new Greeter() { prefix = "Hello" };
      doit(foo.greet);

      // pass doit a Greeter method bound to instance bar
      Greeter bar = new Greeter() { prefix = "Bonjour" };
      doit(bar.greet);

      // pass doit a closure bound to the local variable prefix
      string prefix = "Goodbye";
      doit(( who) => prefix + " " + who );
   }
}

Output:

Hello World
Bonjour World
Goodbye World
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜