C#中的静态事件的消极方面/坏习惯 [英] Negative Aspects/Bad Practice of Static Event in C#

查看:116
本文介绍了C#中的静态事件的消极方面/坏习惯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我创建将在应用程序的不同区域使用的事件时,我会重复使用下面的代码。我发现它非常有用,它使代码中很容易遵循事件。有什么理由这可能是一个坏主意吗?这有点宽泛,但基本上是有理由不这样做?

I reuse the code below a lot when I create events that will be used in different areas of an application. I find it really helpful and it makes events very easy to follow in the code. Is there any reason why this could be a bad idea? This is a bit broad, but basically is there a reason not to do this?

事件类:

public delegate void FocusEventHandler(object source, FocusEventArgs e);

class FocusEvent
{
    public static event FocusEventHandler focusEvent;

    public static void Focus(bool status)
    {
        focusEvent(null, new FocusEventArgs(status));
    }
}

public class FocusEventArgs : EventArgs
{
    public bool Focused { get; set; }

    public FocusEventArgs(bool f)
    {
        Focused = f;
    }
}

所以我需要的是:

FocusEvent.Focus(false);

谢谢你们。这有很多帮助。我真的需要阅读内存使用情况。

Thanks guys. This helps a lot. I really need to read up on memory usage.

推荐答案

static 事件是你需要真的小心地取消订阅。使用实例事件,如果您不取消订阅,那么您可能会最终将图形的一部分人为活动,直到事件被释放的对象不可达(使所有订阅者无法访问) - 然而, static 事件永远不会达到。这意味着任何不取消订阅的订阅者都将永远不会不可访问,并且永远不会被垃圾回收。

The single biggest problem with static events is that you need to be really careful about unsubscribing from them. With an instance event, if you don't unsubscribe then you might end up keeping part of a graph artificially alive until the object with the event is released and is unreachable (making all the subscribers unreachable) - however, a static event never becomes unreachable. This means that any subscribers that don't unsubscribe will never be unreachable, and will never be garbage collected.

这篇关于C#中的静态事件的消极方面/坏习惯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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