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

 

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

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

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

  生成解决方案,报错如下:   
私有构造函数的特点和用途

 

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

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

生成解决方案,报错如下:
私有构造函数的特点和用途

 

□ 私有构造函数的应用

有些时候,我们不希望一个类被过多地被实例化,比如有关全局的类、路由类等。这时候,我们可以为类设置构造函数并提供静态方法。

    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";
        }
    }

 

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

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-10
  • 2022-12-23
  • 2022-02-27
  • 2022-02-06
猜你喜欢
  • 2021-11-03
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-02
相关资源
相似解决方案