设置一个事件为Null

编程入门 行业动态 更新时间:2024-10-09 09:24:11
本文介绍了设置一个事件为Null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个code是这样的:

I have a code like this:

public class SomeClass { int _processProgress; public int ProcessProgress { get { return _processProgress; } set { _processProgress = value; if (ProcessProgressChanged != null) ProcessProgressChanged(value); } } public delegate void ProcessProgressChangedEventHandler(int progressPercentage); public event ProcessProgressChangedEventHandler ProcessProgressChanged; public void ClearProcessProgressChangedEvent() { this.ProcessProgressChanged = null; } }

请问它的退订的的时候,我称之为 ProcessProgressChanged 事件的所有方法 ClearProcessProgressChangedEvent()的方法?

Will it unsubscribe all method in the ProcessProgressChanged event when I call the ClearProcessProgressChangedEvent() method?

我的code是在C#中,框架4,建立在VS2010临,项目是的WinForms。

My code is in C#, framework 4, build in VS2010 Pro, project is in Winforms.

请帮忙。先谢谢了。

推荐答案

嗯,这将有效地清除用户的名单,是的(底层委托字段设置为空) - 使下一次 ProcessProgress 时,没有处理程序将被调用。它不是真正的设置的事件到空 - 这是基础字段设置为空。这只是C#编译器是创建两个事件(一个订阅/退订对方法)和场(存储处理器)使用单一的声明。

Well, it'll effectively clear the list of subscribers, yes (by setting the underlying delegate field to null) - so that the next time ProcessProgress is set, no handlers will be called. It's not really setting the event to null - it's setting the underlying field to null. It's just that the C# compiler is creating both an event (a subscribe/unsubscribe pair of methods) and a field (to store the handlers) using a single declaration.

您可能会发现我的关于事件和委托的有用的文章。

You may find my article about events and delegates useful.

请注意您的活动筹集code目前不是线程安全的。我不知道是否它需要或没有,但你可能想的认为的使用:

Note that your event-raising code currently isn't thread-safe. I don't know whether it needs to be or not, but you might want to consider using:

set { _processProgress = value; var handlers = ProcessProgressChanged; if (handlers != null) { handlers(value); } }

这样,你不会得到一个的NullReferenceException 如果最后的处理程序是退订的在的的无效检查,但的在调用。

That way you won't get a NullReferenceException if the last handler is unsubscribed after the nullity check but before the invocation.

更多推荐

设置一个事件为Null

本文发布于:2023-07-21 07:22:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1175405.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:事件   Null

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!