C#Singleton"GetInstance"方法或"实例"属性?

jla*_*ang 8 c# singleton instance

从谁需要"得到一个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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Noo*_*ilk 16

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


RaY*_*ell 14

如果你想创建单例,你不能只在每个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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

  • @Ty - 如果你取消私人ctor,那么就会有一个隐含的*public*ctor - 而不是我们想要的.是的:对于单身人士,你绝对应该重新使用`instance`(或类似的). (3认同)
  • 所有有效点; 它应该也可能是"密封的". (2认同)