C#是否支持绑定方法或方法闭包(特殊关闭允许它始终指向实例)

时间:2010-12-19 10:16:51

标签: c#

Adob​​e有一个非常明确的解释here

绑定方法(有时称为方法闭包)是从其实例中提取的方法。绑定方法的示例包括作为参数传递给函数或作为函数的值返回的方法。绑定方法类似于函数闭包,因为即使从其实例中提取它也会保留其词法环境。但是,绑定方法和函数闭包之间的关键区别在于绑定方法的this引用仍然与实现该方法的实例相关联或绑定。换句话说,绑定方法中的this引用始终指向实现该方法的原始对象。对于函数闭包,this引用是通用的,这意味着它指向函数在调用时与之关联的任何对象。

如果C#支持泛型闭包,是否有办法将其转换为更方便的绑定方法,因为它真的很烦人且不自然而不能使用它并且人为地使用发送者而不是最重要的是必须明确地传递发送者对象,而不是能够使用隐含的this关键字。

1 个答案:

答案 0 :(得分:2)

是的,鉴于该定义,C#支持“绑定方法”。

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 );
   }
}

输出:

Hello World
Bonjour World
Goodbye World