私有构造函数的特色和用途

本篇体验私有构造函数的特色,以及在何种状况下使用私有构造函数。函数

 

□ 带私有构造函数的类不能被继承spa

在Animal类中声明一个私有构造函数,让Dog类来继承Animal类。
blog

    public class Animal
    {
        private Animal()
        {
            Console.WriteLine("i am animal");
        }
    }
    public class Dog : Animal
    {
        
    }

  生成解决方案,报错以下:   
1继承

 

□ 带私有构造函数的类不能被实例化路由

    class Program
    {
        static void Main(string[] args)
        {
            Animal animal = new Animal();
        }
    }
    public class Animal
    {
        private Animal()
        {
            Console.WriteLine("i am animal");
        }
    }

生成解决方案,报错以下:
2get

 

□ 私有构造函数的应用string

有些时候,咱们不但愿一个类被过多地被实例化,好比有关全局的类、路由类等。这时候,咱们能够为类设置构造函数并提供静态方法。it

    class Program
    {
        static void Main(string[] args)
        {
            string str = Animal.GetMsg();
            Console.WriteLine(str);
            Console.ReadKey();
        }
    }
    public class Animal
    {
        private Animal()
        {
            Console.WriteLine("i am animal");
        }
        public static string GetMsg()
        {
            return "Hello World";
        }
    }

 

总结:一旦一个类被设置成私有构造函数,就不能被继承,不能被实例化,这种状况下,一般为类提供静态方法以供调用。class

相关文章
相关标签/搜索