Adobe有非常明确的解释here http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7f30.html#WS5b3ccc516d4fbf351e63e3d118a9b90204-7fcb:
绑定方法(有时称为方法闭包)是从其实例中提取的方法。绑定方法的示例包括作为参数传递给函数或从函数作为值返回的方法。绑定方法与函数闭包类似,即使从其实例中提取,它也保留其词法环境。然而,绑定方法和函数闭包之间的主要区别在于,绑定方法的 this 引用仍然链接或绑定到实现该方法的实例。换句话说,绑定方法中的 this 引用始终指向实现该方法的原始对象。对于函数闭包, this 引用是通用的,这意味着它指向函数被调用时与之关联的任何对象。
如果 C# 支持泛型闭包,有没有办法将其变成更方便的绑定方法,因为不能使用它并人为地使用 sender 来代替确实很烦人且不自然,而且最重要的是必须显式传递 sender 对象而不是能够使用隐式的 this 关键字。
是的,根据该定义,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 );
}
}
Output:
Hello World
Bonjour World
Goodbye World
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)