C# 单例“GetInstance”方法还是“Instance”属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1360482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 15:37:33  来源:igfitidea点击:

C# Singleton "GetInstance" Method or "Instance" Property?

c#singletoninstance

提问by jlang

From the perspective of an API end-user who needs to "get anthe instance" of a Singleton class, do you prefer to "get" anthe .Instance property or "call" a .GetInstance() Method?

从谁需要“得到一个API最终用户的角度来看一个实例”一个Singleton类的,你喜欢“获得”一个在.Instance属性或“呼叫”一.GetInstance()方法?

public class Bar
{
    private Bar() { }

    // Do you prefer a Property?
    public static Bar Instance
    {
        get
        {
            return new Bar();
        }
    }

    // or, a Method?
    public static Bar GetInstance()
    {
        return new Bar();
    }
}

采纳答案by Noon Silk

In C#, I would far prefer .Instance, as it fits in with the general guidelines.

在 C# 中,我更喜欢.Instance,因为它符合一般准则。

回答by Michael Todd

Depends. Do you need to pass parameters? If so, I'd do GetInstance(). If not, probably doesn't matter (at least from a calling standpoint, since they're really both methods anyway; however, it doesmatter if you're trying to be more standards-based and, in that case, an instance appears to be better).

要看。需要传递参数吗?如果是这样,我会做 GetInstance()。如果不是,则可能无关紧要(至少从调用的角度来看,因为无论如何它们实际上都是两种方法;但是,如果您尝试更加基于标准,并且在这种情况下会出现一个实例,这确实很重要变得更好)。

回答by Athiwat Chunlakhan

I prefer property, these are standard patterns.

我更喜欢财产,这些是标准模式。

回答by Rex M

As with just about everything, it depends :)

与几乎所有事情一样,这取决于:)

If the singleton is lazy-loaded and represents more than a trivial amount of work to instantiate, then GetInstance() is more appropriate, as a method invocation indicates work is being done.

如果单例是延迟加载的并且表示要实例化的工作量不仅仅是微不足道的,那么 GetInstance() 更合适,因为方法调用表明工作正在完成。

If we're simply masking to protect the singleton instance, a property is preferable.

如果我们只是简单地屏蔽以保护单例实例,则最好使用属性。

回答by RaYell

If you want to create singleton you cannot just return new object on every GetInstancecall or Instanceproperty getter. You should do something like this:

如果你想创建单例,你不能在每次GetInstance调用或Instance属性 getter 时只返回新对象。你应该做这样的事情:

public sealed class Bar
{
    private Bar() { }

    // this will be initialized only once
    private static Bar instance = new Bar();

    // Do you prefer a Property?
    public static Bar Instance
    {
        get
        {
            return instance;
        }
    }

    // or, a Method?
    public static Bar GetInstance()
    {
        return instance;
    }
}

And it doesn't really matter which way of doing that you choose. If you prefer working with properties choose it, if you prefer methods it will be ok as well.

你选择哪种方式并不重要。如果您更喜欢使用属性,请选择它,如果您更喜欢方法,也可以。

回答by Franci Penov

As @Rex said, it depends on the semantic you want to convey.

正如@Rex 所说,这取决于您想要传达的语义。

GetInstance() does not necessarily imply a singleton instance. So, I would use GetInstance() in the case where the instance creation happens on demand, direct new is not desireable and the instance could be, but is not guaranteed to be the same. Object pools fit these criteria as well. (In fact, a singleton is a specialization of an object pool with state preservation :-))

GetInstance() 不一定意味着单例实例。所以,我会在实例创建按需发生的情况下使用 GetInstance(),直接 new 是不可取的,实例可能是,但不能保证是相同的。对象池也符合这些标准。(实际上,单例是具有状态保存的对象池的特化 :-))

Static Instance property on the other hand implies a singleton and preserved instance identity.

另一方面,静态实例属性意味着单例和保留的实例标识。

Btw, as @RaYell mentioned your sample code is not a singleton, so you shouldn't be using Instance property. You can still use the GetInstance() method in this case, as it would serve as an instance factory.

顺便说一句,正如@RaYell 提到的,您的示例代码不是单例,因此您不应使用 Instance 属性。在这种情况下,您仍然可以使用 GetInstance() 方法,因为它将用作实例工厂。

回答by Raghav

public class Singleton
{

    private volatile static Singleton uniqueInstance;
    private static readonly object padlock = new object();

    private Singleton() { }

    public static Singleton getInstance()
    {
        if (uniqueInstance == null)
        {
            lock (padlock)
            {
                if (uniqueInstance == null)
                {
                    uniqueInstance = new Singleton();
                }
            }
        }
        return uniqueInstance;
    }
}

In the above code double checking is implemented ,first it is checked if an instance is is created and if not lock has been established .Once in this block

在上面的代码中实现了双重检查,首先检查是否创建了一个实例,如果没有建立锁。一旦在这个块中

                if (uniqueInstance == null)
                {
                    uniqueInstance = new Singleton();
                }

if the instance is null then create it.

如果实例为空,则创建它。

Also, the uniqueInstance variable is declared to be volatile to ensure that assignment to the instance variable completes before the instance variable can be accessed.

此外,uniqueInstance 变量被声明为 volatile 以确保在可以访问实例变量之前完成对实例变量的赋值。