最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#中私有構(gòu)造函數(shù)的特點(diǎn)和用途實(shí)例解析

 更新時(shí)間:2014年08月13日 10:10:20   投稿:shichen2014  
這篇文章主要介紹了C#中私有構(gòu)造函數(shù)的特點(diǎn)和用途,需要的朋友可以參考下

本文以實(shí)例形式分析私有構(gòu)造函數(shù)的特點(diǎn),以及在何種情況下使用私有構(gòu)造函數(shù)。相信對(duì)于大家更好的理解C#中的私有構(gòu)造函數(shù)有一定的促進(jìn)作用。具體如下:

一、帶私有構(gòu)造函數(shù)的類不能被繼承

在Animal類中聲明一個(gè)私有構(gòu)造函數(shù),讓Dog類來(lái)繼承Animal類。

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

運(yùn)行程序,生成解決方案,報(bào)錯(cuò)如下圖所示:

二、帶私有構(gòu)造函數(shù)的類不能被實(shí)例化

運(yùn)行如下測(cè)試代碼:

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

程序運(yùn)行后生成解決方案,報(bào)錯(cuò)如下圖所示:

三、私有構(gòu)造函數(shù)的應(yīng)用

有些時(shí)候,我們不希望一個(gè)類被過(guò)多地被實(shí)例化,比如有關(guān)全局的類、路由類等。這時(shí)候,我們可以為類設(shè)置構(gòu)造函數(shù)并提供靜態(tài)方法。

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

總結(jié):一旦一個(gè)類被設(shè)置成私有構(gòu)造函數(shù),就不能被繼承,不能被實(shí)例化,這種情況下,通常為類提供靜態(tài)方法以供調(diào)用。

相關(guān)文章

最新評(píng)論

SHOW| 平远县| 东至县| 塘沽区| 博兴县| 博白县| 盐边县| 遂溪县| 新昌县| 平舆县| 万安县| 镇江市| 灵石县| 阳谷县| 双城市| 毕节市| 金乡县| 赤水市| 商丘市| 珲春市| 原平市| 保定市| 屏东市| 尼木县| 桐庐县| 马尔康县| 鹿邑县| 西贡区| 津市市| 西藏| 宜黄县| 荣昌县| 高尔夫| 张家港市| 开平市| 固原市| 通道| 双峰县| 汝城县| 河源市| 加查县|