简体   繁体   English

C# 闭包绑定

[英]C# Closure binding

Given the following, when is foo bound?鉴于以下情况, foo何时绑定?

 System.Timer t = new System.Timer( (a)=>{
    var foo = Messages.SelectedItem as FooBar;
 });

Is it bound then the anonymous method is executed, or when the method is defined?它是绑定然后执行匿名方法,还是在定义方法时?

Never, because of the compile-time error you would get due the absence of a System.Timer class in the BCL.永远不会,因为 BCL 中没有System.Timer class 会导致编译时错误。 Assuming you wanted a System.Threading.Timer then the closure will be bound/captured at the moment this constructor is called ie the method is defined.假设你想要一个System.Threading.Timer ,那么在调用这个构造函数的那一刻,闭包将被绑定/捕获,即方法被定义。 If you want to bind it when the method is executed you need another constructor overload and pass a state.如果要在方法执行时绑定它,则需要另一个构造函数重载并传递 state。

var t = new System.Threading.Timer(a =>
{
    var foo = a as FooBar;
}, Messages.SelectedItem, -1, -1);

Now when the callback runs it will use the Messages.SelectedItem value at the moment this callback executes.现在,当回调运行时,它将在回调执行时使用Messages.SelectedItem值。

foo is not bound at all, as it's internal to the anonymous method. foo根本没有绑定,因为它是匿名方法的内部。 It will call Messages.SelectedItem.它将调用 Messages.SelectedItem。 If Messages is an instance property, what is bound is the 'this' instance, which is used to get at Messages.如果 Messages 是一个实例属性,则绑定的是 'this' 实例,它用于获取 Messages。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM