获得改良的封闭物(2) [英] Access to Modified Closure (2)
问题描述
这是问题的访问修改关闭的延伸。我只是想验证下其实是足够安全的生产环境。
名单,其中,串>名单=新的名单,其中,串>();
// code检索数据库列表
的foreach(列表中的字符串列表)
{
按钮BTN =新按钮();
btn.Click + =新的EventHandler(委托{的MessageBox.show(名单);});
}
我只能通过上面的每一次启动时运行。现在它似乎工作好了。正如乔恩提及违反直觉的结果,在某些情况下。所以我需要在这里看什么?会不会是确定的,如果该列表是通过不止一次?
运行在此之前的C#5,您需要重新声明一个变量的在的在foreach - 否则它是共同的,所有的处理程序将使用最后一个字符串:
的foreach(字符串列表中列出)
{
字符串TMP =清单;
按钮BTN =新按钮();
btn.Click + =新的EventHandler(委托{的MessageBox.show(TMP);});
}
值得注意的是,请注意,从C#5起,这种情况已经改变,而具体的的foreach
的,你并不需要做的情况下,这更多:在code的问题将能按预期效果
为了说明这一点没有工作没有这种变化,考虑以下几点:
字符串[]名称= {弗雷德,巴尼,贝蒂,威尔玛};
使用(Form表单=新表())
{
的foreach(在名称字符串名称)
{
按钮BTN =新按钮();
btn.Text =名称;
btn.Click + =委托
{
的MessageBox.show(形式名称);
};
btn.Dock = DockStyle.Top;
form.Controls.Add(BTN);
}
Application.Run(形式);
}
运行上面的之前,C#5 ,虽然每个按钮显示一个不同的名称,点击按钮显示威尔玛的四倍。
这是因为语言规范(ECMA 334第4版,15.8.4)(前C#5)定义:
的foreach(V V IN X)
的嵌入语句
的再扩展到{ E E =((C)(X))的GetEnumerator()。 尝试 { V伏; 而(e.MoveNext()){ V =(V)(T)e.Current; 嵌入语句 } } 最后 { ... //处置Ë } }
注意变量 v
(这是你的列表
)声明的 的外循环。因此,通过捕获变量的规则,列表的所有迭代将共享捕获变量保持器
从C#5起,这是变了:迭代变量( v
)的作用范围在的循环。我没有规范的参考,但它基本上变成:
{
E E =((C)(X))的GetEnumerator()。
尝试 {
而(e.MoveNext()){
V V =(V)(T)e.Current;
嵌入语句
}
}
最后 {
... //处置Ë
}
}
回复退订;如果你主动要取消匿名处理,关键是要捕捉处理程序本身:
事件处理程序富=委托{... code ...};
obj.SomeEvent + = foo的;
...
obj.SomeEvent - = foo的;
同样的,如果你想有一个一次性的事件处理程序(如负载等):
事件处理程序栏= NULL; //必要明确赋值
巴=委托{
// ... code
obj.SomeEvent - =吧;
};
obj.SomeEvent + =酒吧;
这是目前自主退订;-p
This is an extension of question from Access to Modified Closure. I just want to verify if the following is actually safe enough for production use.
List<string> lists = new List<string>();
//Code to retrieve lists from DB
foreach (string list in lists)
{
Button btn = new Button();
btn.Click += new EventHandler(delegate { MessageBox.Show(list); });
}
I only run through the above once per startup. For now it seems to work alright. As Jon has mentioned about counterintuitive result in some case. So what do I need to watch out here? Will it be ok if the list is run through more than once?
Prior to C# 5, you need to re-declare a variable inside the foreach - otherwise it is shared, and all your handlers will use the last string:
foreach (string list in lists)
{
string tmp = list;
Button btn = new Button();
btn.Click += new EventHandler(delegate { MessageBox.Show(tmp); });
}
Significantly, note that from C# 5 onwards, this has changed, and specifically in the case of foreach
, you do not need to do this any more: the code in the question would work as expected.
To show this not working without this change, consider the following:
string[] names = { "Fred", "Barney", "Betty", "Wilma" };
using (Form form = new Form())
{
foreach (string name in names)
{
Button btn = new Button();
btn.Text = name;
btn.Click += delegate
{
MessageBox.Show(form, name);
};
btn.Dock = DockStyle.Top;
form.Controls.Add(btn);
}
Application.Run(form);
}
Run the above prior to C# 5, and although each button shows a different name, clicking the buttons shows "Wilma" four times.
This is because the language spec (ECMA 334 v4, 15.8.4) (before C# 5) defines:
foreach (V v in x)
embedded-statement
is then expanded to:{ E e = ((C)(x)).GetEnumerator(); try { V v; while (e.MoveNext()) { v = (V)(T)e.Current; embedded-statement } } finally { … // Dispose e } }
Note that the variable v
(which is your list
) is declared outside of the loop. So by the rules of captured variables, all iterations of the list will share the captured variable holder.
From C# 5 onwards, this is changed: the iteration variable (v
) is scoped inside the loop. I don't have a specification reference, but it basically becomes:
{
E e = ((C)(x)).GetEnumerator();
try {
while (e.MoveNext()) {
V v = (V)(T)e.Current;
embedded-statement
}
}
finally {
… // Dispose e
}
}
Re unsubscribing; if you actively want to unsubscribe an anonymous handler, the trick is to capture the handler itself:
EventHandler foo = delegate {...code...};
obj.SomeEvent += foo;
...
obj.SomeEvent -= foo;
Likewise, if you want a once-only event-handler (such as Load etc):
EventHandler bar = null; // necessary for "definite assignment"
bar = delegate {
// ... code
obj.SomeEvent -= bar;
};
obj.SomeEvent += bar;
This is now self-unsubscribing ;-p
这篇关于获得改良的封闭物(2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!