简体   繁体   中英

Referencing an instantiated object in a static class (c#)

I am wondering if it is possible to have a static class instantiate another class for the purpose of holding a reference to it globally. I have a data store which is composed of an in-memory object and would like to access it from different locations. The data needs to persist changes to the application so it needs to be instantiated outside of window or UI scope.

I was hoping that using a static class to do this would be the correct way of doing it. Is this what a singleton is? Is what I am looking for possible?

The normal way of handling this is to use the Singleton Pattern . This basically creates a single instance of a non-static class, which can be accessed statically (typically by using the ClassName.Instance property).

Here's a great page on creating a singleton in C# .

Here is a simple example.... you could get the property just by using Config.Instance.Value

public class Config
{
    private Config() 
    {
        this.Value = "foobarr";
    }
    private static object _syncLock = new object();
    private static Config _instance;
    public static Config Instance
    {
        get
        {
            lock (_syncLock)
            {
                if (_instance == null)
                    _instance = new Config();
                return _instance;
            }
        }
    }

    public string Value { get; private set; }
}

A static class can create and reference any object just like any other class. It's not quite a singleton, but you get a similar end result. The static class is "constructed" the first time it is referenced, so if you need something to happen before the window or UI stuff happens you'll still need to take care of that.

Whether an actual singleton is better, I don't know. There are quite a few people out there that say singletons and static classes are bad, mostly because they make the code a little more rigid. It's almost a global variable in a way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM