当前位置:首页 > IT技术 > Windows编程 > 正文

记《learning hard C#学习笔记》 书中一个错误
2021-08-08 12:11:03

以前学过c# 但是不够系统

最近读了一本《learning hard C#学习笔记》 系统的学习一下

读到50页 发现一个问题,这本书用的单例有问题 记《learning hard C#学习笔记》 书中一个错误_构造方法

 

主要问题:

1 首先public static Person person 这里的public 就有问题  单例里面 这里应该是private

2 在GetInstance方法里面  person = new Person() 这句不对

这样每次调用GetInstance方法都会new一个Person对象出来

就不是单例

线程完全问题等暂且不谈。

 

两次通过GetInstance()方法获取 Person实例。

发现 私有构造器方法被调用两次且

用==去判断发现,两次获取的Person实例并不相同。

因此不是单例。

 

记《learning hard C#学习笔记》 书中一个错误_构造方法_02

对Person类作如下改动:

 

    class Person
    {

        private string name;
        private static Person person;
        public string Name
        {
            get { return name; }
        }

        private Person()
        {
            Console.WriteLine("私有构造方法被调用");
            this.name = "learning hard";
        }

        public static Person getInstance()
        {
            if (person == null)
            {
                person = new Person();
            }
            return person;
        }

    }


运行:

 

 

    class Program
    {
        static void Main(string[] args)
        {
            Person person1 = Person.getInstance();
            Person person2 = Person.getInstance();

            Console.WriteLine("单例是否有效:{0}", person1 == person2);
            Console.WriteLine("类实例的name属性为:{0}",person1.Name);
            Console.Read();
        }
    }

 

 

 

运行结果:
记《learning hard C#学习笔记》 书中一个错误_c#_03

 

其次 个人建议方法名用小驼峰命名法

获取实例的方法名用getInstance比较合适

 

本文摘自 :https://blog.51cto.com/u