它是不好的做法,有一个静态类的状态? [英] Is it bad practice to have state in a static class?

查看:136
本文介绍了它是不好的做法,有一个静态类的状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我愿做这样的事情:

public class Foo {
    // Probably really a Guid, but I'm using a string here for simplicity's sake.
    string Id { get; set; }

    int Data { get; set; }

    public Foo (int data) {
        ...
    }

    ...
}

public static class FooManager {
    Dictionary<string, Foo> foos = new Dictionary<string, Foo> ();

    public static Foo Get (string id) {
        return foos [id];
    }

    public static Foo Add (int data) {
        Foo foo = new Foo (data);
        foos.Add (foo.Id, foo);

        return foo;
    }

    public static bool Remove (string id) {
        return foos.Remove (id);
    }

    ...

    // Other members, perhaps events for when Foos are added or removed, etc.
}

这将让我管理的全球系列S从任何地方。不过,我已经告诉静态类应该始终是无状态的 - 你不应该使用它们来存储全局数据。一般全局数据似乎在被皱起了眉头。 ?如果我不应该使用一个静态类,什么是解决这个问题的正确方法。

This would allow me to manage the global collection of Foos from anywhere. However, I've been told that static classes should always be stateless--you shouldn't use them to store global data. Global data in general seems to be frowned upon. If I shouldn't use a static class, what is the right way to approach this problem?

请注意:我没有找到一个的similar问题,但给出的答复并不在我的情况真的很适用。

Note: I did find a similar question, but the answer given doesn't really apply in my case.

推荐答案

谁留静态类应该是无状态的?静态的办法的说明

Who stays that static classes should be stateless? Static means stated.

只要知道类是如何静态的CLR工作:

Just know how static classes work in the CLR:


  • 您无法控制时,静态构造函数的调用时间。

  • 静态类为每个调用程序一个独立的国家。

另外要注意的并发问题。

Also be aware of concurrency issues.

作为一个侧面说明,它使我惊奇人们经常说不要用X.这就像有人走进你的工具室,指着半打工具和说:这些工具是不好的做法。它没有意义。

As a side note, it amazes me how often people say "Don't use X." It would be like someone walking into your toolshed and pointing to half a dozen tools and saying, "Those tools are bad practice." It doesn't make sense.

这篇关于它是不好的做法,有一个静态类的状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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