事件可以被声明为静态的,如果是怎样和为什么 [英] Can Events be declared as Static, if yes how and why

查看:109
本文介绍了事件可以被声明为静态的,如果是怎样和为什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道我们可以声明事件作为静态如果是为何而该声明的应用程序。

I want to know can we declare the events as static if yes why and application of such declaration.

样品请为眼见为实

推荐答案

您可以创建静态事件。您可以使用它们以同样的方式作为一个正常的事件,不同的是它在类中的一个静态的环境中使用。

You can create static events. You use them the same way as a normal event, except that it's used in a static context within the class.

public class MyClass
{
    public static event EventHandler MyEvent;

    private static void RaiseEvent()
    {
        var handler = MyEvent;
        if (handler != null)
            handler(typeof(MyClass), EventArgs.Empty);
    }
}



话虽这么说,也有静态的事件很多问题。你必须格外小心,退订的静态事件的对象,因为订阅了静态事件将根你的订阅情况,并防止垃圾收集器从不断收集它。

That being said, there are many issues with static events. You must take extra care to unsubscribe your objects from static events, since a subscription to a static event will root your subscribing instance, and prevent the garbage collector from ever collecting it.

另外,我发现,大多数情况下,我愿意做静态的活动,我倾向于对学习上使用的辛格尔顿代替的。这将在同一场景为静态事件,而是(IMO)更为明显,你订阅了全局级别的实例。

Also, I've found that most cases where I'd want to make static events, I tend to learn towards using a standard event on a Singleton instead. This handles the same scenarios as a static event, but is (IMO) more obvious that you're subscribing to a "global" level instance.

这篇关于事件可以被声明为静态的,如果是怎样和为什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆