本文介绍了访问修改的关闭(2)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是问题的扩展。我只想验证以下是否真的足够安全用于生产使用。

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); });
}

我每次启动只运行一次。现在它似乎工作好了。正如Jon在某些情况下提到了违反直觉的结果。那么我需要在这里注意什么?

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?

推荐答案

在C#5之前,您需要重新声明在foreach中的变量 - 否则它是共享的,并且所有的处理程序将使用最后一个字符串:

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); });
}

值得注意的是,从C#5开始, >特别是在 foreach 的情况下,您不需要这样做:问题中的代码将按预期工作。

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);
}

运行上述之前的C#5

这是因为语言规格(ECMA 334 v4,15.8.4)(之前是C#5)定义:

This is because the language spec (ECMA 334 v4, 15.8.4) (before C# 5) defines:

{
    E e = ((C)(x)).GetEnumerator();
    try {
        V v;
         while (e.MoveNext()) {
            v = (V)(T)e.Current;
             embedded-statement
        }
    }
    finally {
        … // Dispose e
    }
}


注意变量 v 您的列表)被声明为 。因此,通过捕获变量的规则,列表的所有迭代将共享捕获的变量持有人。

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.

从C#5开始,改变:迭代变量c $ c> v )作用域内。我没有规范参考,但它基本上变成:

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;

同样,如果你想要一个一次性的事件处理程序p>

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;

现在是自动取消订阅;-p

This is now self-unsubscribing ;-p

这篇关于访问修改的关闭(2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 19:56