C#中私有构造函数的特点和用途实例解析


本文以实例形式分析私有构造函数的特点,以及在何种情况下使用私有构造函数。相信对于大家更好的理解C#中的私有构造函数有一定的促进作用。具体如下:

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

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

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


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3