C# Closure binding
Given the following, when is foo
bound?
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?
foo
is not bound at all, as it's internal to the anonymous method. It will call Messages.SelectedItem. If Messages is an instance property, what is bound is the 'this' instance, which is used to get at Messages.
Never, because of the compile-time error you would get due the absence of a System.Timer
class in the BCL. Assuming you wanted a System.Threading.Timer then the closure will be bound/captured at the moment this constructor is called i.e. the method is defined. If you want to bind it when the method is executed you need another constructor overload and pass a 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.
精彩评论