[英]How can I safely unsubscribe from an Action in one line?
I would like to know if I can unsubscribe from a C# Action in a safe way in just one line of code instead of having to write this: 我想知道我是否可以在一行代码中以安全的方式取消订阅C#Action而不必写这个:
if(publisher.RaiseCustomEvent != null)
{
publisher.RaiseCustomEvent -= HandleCustomEvent;
}
A simple example: 一个简单的例子:
public class Publisher
{
public Action RaiseCustomEvent;
public MyClass() { }
}
public class Subscriber
{
Publisher _publisher;
public Subscriber()
{
_publisher = new Publisher();
_publisher.RaiseCustomEvent += HandleCustomEvent;
}
// ...
public void Dispose()
{
// DO this safely in one line
if(_publisher.RaiseCustomEvent != null)
{
_publisher.RaiseCustomEvent -= HandleCustomEvent;
}
}
}
if I can unsubscribe from a C# Action in a safe way in just one line of code
如果我可以在一行代码中以安全的方式取消订阅C#Action
Yes, you don't even need the null check: 是的,你甚至不需要空检查:
//if(publisher.RaiseCustomEvent != null)
{
publisher.RaiseCustomEvent -= HandleCustomEvent;
}
and then you can clean that up of course. 然后你可以清理它当然。
This is null-safe, probably not thread-safe. 这是空安全的,可能不是线程安全的。
Since an event starts out as null
you have to be able to subscribe with +=
on a null delegate. 由于事件以
null
开头,因此您必须能够在null委托上使用+=
进行订阅。 The same holds for unsubscribing. 取消订阅同样适用。
I don't even think it matters whether RaiseCustomEvent is an event
or an Action field. 我甚至认为RaiseCustomEvent是一个
event
还是一个Action字段并不重要。 But please be clear about that. 但请明确这一点。
You do of course have to make sure that you raise the event in a null-safe way, either with if ( ... != null)
or with a ?.Invoke()
. 你当然必须确保以null安全的方式引发事件,使用
if ( ... != null)
或使用?.Invoke()
。
Now that you have posted the code, your RaiseCustomEvent
is a public field. 现在您已经发布了代码,您的
RaiseCustomEvent
是一个公共字段。 That has some drawbacks with regard to encapsulation. 这在封装方面有一些缺点。 Using an event is the common practice:
使用事件是常见的做法:
public class Publisher
{
//public Action RaiseCustomEvent;
public event Action RaiseCustomEvent;
}
This will only allow +=
and -=
, and prevents overwriting with RaiseCustomEvent = MySingleMethod
这将只允许
+=
和-=
,并防止使用RaiseCustomEvent = MySingleMethod
覆盖
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.