设置一个事件为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.