Is implementing a singleton using an auto-property a good idea?

前端 未结 6 1101
时光取名叫无心
时光取名叫无心 2021-01-02 05:13

I recently found out about auto-properties and like them quite a lot. At this moment I am trying to use them everywhere where I can. Not really to just be able to use them e

6条回答
  •  礼貌的吻别
    2021-01-02 05:51

    I wouldn't personally do that. I don't like using automatically implemented properties with a private setter that you never call where really you want a read-only property backed by a read-only variable. It's only one more line of code to be more explicit about what you mean:

    public sealed class MySingleton
    {
        private static readonly MySingleton mySingleton;
        public static MySingleton MySingleton { get { return mySingleton; } }
    
        private MySingleton() {}
    
        static MySingleton() { mySingleton = new MySingleton(); }
    }
    

    This way no-one's even tempted to change the singleton class to reassign either the property or the variable, because the compiler will stop them. They'd have to add a setter and/or make the variable non-readonly, which is a bigger change - one which hopefully they'd reconsider.

    In other words:

    • Yes, it will work.
    • No, I don't think it's a good idea.

    As of C# 6, this is easier with read-only automatically implemented properties though:

    public sealed class MySingleton
    {
        public static MySingleton MySingleton { get; } = new MySingleton();    
        private MySingleton() {}         
        static MySingleton() {}
    }
    

提交回复
热议问题