考虑这个人为的例子:
public static class Test {
private static List<Action> actions = new List<Action>();
private static Int32 _foo = 123;
public static void Foo() {
Int32 foo = _foo += 123;
Object bar = new Object();
IDisposable baz = GetExpensiveObject();
Action callback = new Action(delegate() {
DoSomething( foo, bar, baz );
baz.Dispose();
});
foo = 456;
bar = new Object();
actions.Add( callback );
}
public static void Main() {
Foo();
Foo();
foreach(Action a in actions) a();
}
}
看Main
,假设Foo
调用了两次,然后执行actions
(到现在,2个实例)的内容,Action
变量的状态是什么?foo
bar
baz
callback
如果callback
从不被调用,将baz
永远被处置(因为包含在callback
内的引用actions
?),那么actions.Clear()
被调用的东西会baz
被处置吗?
(我不在一台装有编译器或 IDE 的计算机上供我测试)