有没有办法在不失去范围的情况下添加和分离事件处理程序?

发布于 2024-12-06 20:08:07 字数 664 浏览 0 评论 0原文

使用异步类时,我经常发现我总是必须将状态存储在字段中,以便我可以在完成的方法中访问它们。理想情况下,我希望避免在字段中存储状态,因为这意味着我需要担心进行的多次调用及其对字段数据的影响。

我编写的这段代码可以工作,尽管 Resharper 给了我一个“访问修改后的披露”警告。

public void Test(Action<Result> result)
{
    var myClass = new MyClass();
    EventHandler eventHandler = null;
    eventHandler = (s, e) =>
                        {
                            var mc = (MyClass) s;
                            mc.Completed -= eventHandler;
                            result(mc.Result);
                        };
    myClass.Completed += eventHandler;
    myClass.Run();
}

该代码块是否有问题,如果没有,是否有更好的方法来执行此操作,而无需创建字段来存储数据并确保某种程度的范围仍然存在?

Working with asynchronous classes, often I find that I am always having to store state in fields so that I have access to them in the completed method. Ideally, I'd like to avoid having to store state in fields as this means I need to worry about multiple calls being made and their affect on the field data.

I wrote this block of code which could work, although Resharper gives me an 'access to modified disclosure' warning.

public void Test(Action<Result> result)
{
    var myClass = new MyClass();
    EventHandler eventHandler = null;
    eventHandler = (s, e) =>
                        {
                            var mc = (MyClass) s;
                            mc.Completed -= eventHandler;
                            result(mc.Result);
                        };
    myClass.Completed += eventHandler;
    myClass.Run();
}

Is there a problem with this block of code and if not, is there a better way to do this without creating fields to store data and ensure that some level of scope still exists?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

虐人心 2024-12-13 20:08:07

在这种情况下使用匿名委托是绝对没问题的。有关特定 ReSharper 警告的讨论,请参阅以下问题,其中详细讨论了该问题:

访问修改后的闭包< /a>

当您想在首次加载或呈现 UI 时仅执行一次某些代码时,我会使用您在 WPF/Silverlight/WP7 应用程序中经常说明的模式。

Your usage of an anonymous delegate in this context is absolutely fine. For a discussion on the specific ReSharper warning, see the following question which discusses it in detail:

Access to Modified Closure

I use the pattern you have illustrated quite often in WPF / Silverlight / WP7 application when you want to execute some code just once when the UI is first loaded or rendered.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文