鍍金池/ 教程/ C#/ C#類
C#屬性(Properties)
C#與Java比較
C#方法
C#枚舉
C#關(guān)鍵字
C# StreamReader類
C#不安全代碼
C#文件(I/O)
C#匿名方法
C#線程同步
C# Thread類
C#主線程
C#數(shù)據(jù)類型
C# FileStream類
C#預(yù)處理指令
C#繼承
C#循環(huán)
C#決策結(jié)構(gòu)
C#集合
C#反射
C#類型轉(zhuǎn)換
C#泛型
C# StringReader類
C#歷史
C#運算符重載
C#屬性
C#線程實例:Sleep()方法
C#線程示例:優(yōu)先級
C#線程實例:Join()方法
C# BinaryReader類
C#類
C#索引器
C# BinaryWriter類
C#序列化
C#常量和文字
C#程序結(jié)構(gòu)
C#封裝
C#事件
C#可空類型(nullable)
C#基本語法
C#異常處理
C#教程
C#接口
C# System.IO命名空間
C#線程命名實例
C# StringWriter類
C#線程實例
C#數(shù)組
C#正則表達(dá)式
C#命名空間
C#反序列化
C#與C++比較
C# TextWriter類
C#多線程
C#字符串
C#是什么?
C#變量
C# FileInfo類
C#線程實例:Abort()方法
C#結(jié)構(gòu)體
C#運算符
C#入門程序
C#多線程生命周期
C# TextReader類
C# DirectoryInfo類
C#委托

C#類

類是對象的藍(lán)圖或模板,可以定義類來表示某種數(shù)據(jù)類型。這實際上并不定義任何數(shù)據(jù),但它確實定義了類名稱的含義。也就是說,該類的對象由哪個對象組成,哪些對象可以執(zhí)行什么操作。 對象是類的實例。 構(gòu)成類的方法和變量稱為類的成員。

定義一個類

類定義從class關(guān)鍵字開始,后跟類名稱; 和由一對花括號括在一起表示類的主體。 以下是類定義的一般形式:

<access specifier> class  class_name
{
   // member variables
   <access specifier> <data type> variable1;
   <access specifier> <data type> variable2;
   ...
   <access specifier> <data type> variableN;
   // member methods
   <access specifier> <return type> method1(parameter_list)
   {
      // method1 body
   }
   <access specifier> <return type> method2(parameter_list)
   {
      // method2 body
   }
   ...
   <access specifier> <return type> methodN(parameter_list)
   {
      // method3 body
   }
}

注意:

  • 訪問說明符(access specifier)指定成員以及類本身的訪問規(guī)則。如果沒有指定,則類的默認(rèn)訪問說明符是internal。成員的默認(rèn)訪問權(quán)限是private
  • 數(shù)據(jù)類型(data type)指定變量的類型,返回類型(return type)指定方法返回的數(shù)據(jù)的數(shù)據(jù)類型(如果有)。
  • 要訪問類成員,請使用點(.)運算符。
  • 點(.)運算符將對象的名稱與成員的名稱相鏈接。

以下示例說明了上面所討論的概念:

using System;
namespace BoxApplication
{
    class Box
    {
       public double length;   // Length of a box
       public double breadth;  // Breadth of a box
       public double height;   // Height of a box
    }
    class Boxtester
    {
        static void Main(string[] args)
        {
            Box Box1 = new Box();   // Declare Box1 of type Box
            Box Box2 = new Box();   // Declare Box2 of type Box
            double volume = 0.0;    // Store the volume of a box here

            // box 1 specification
            Box1.height = 5.0;
            Box1.length = 6.0;
            Box1.breadth = 7.0;

            // box 2 specification
            Box2.height = 10.0;
            Box2.length = 12.0;
            Box2.breadth = 13.0;

            // volume of box 1
            volume = Box1.height * Box1.length * Box1.breadth;
            Console.WriteLine("Volume of Box1 : {0}",  volume);

            // volume of box 2
            volume = Box2.height * Box2.length * Box2.breadth;
            Console.WriteLine("Volume of Box2 : {0}", volume);
            Console.ReadKey();
        }
    }
}

當(dāng)編譯和執(zhí)行上述代碼時,會產(chǎn)生以下結(jié)果:

Volume of Box1 : 210
Volume of Box2 : 1560

成員函數(shù)和封裝

類的成員函數(shù)是在類中定義具有與其他變量類似的定義或其原型的函數(shù)。它對其所屬類的任何對象進(jìn)行操作,并且可以訪問該對象的類的所有成員。

成員變量是對象的屬性(從設(shè)計的角度),它們被保留為私有(private)以實現(xiàn)封裝。這些變量只能使用公共成員函數(shù)來訪問。

為了理解上面的概念,我們從一個類中設(shè)置并讀取另外一個類的成員的值:

using System;
namespace BoxApplication
{
   class Box
   {
      private double length;   // Length of a box
      private double breadth;  // Breadth of a box
      private double height;   // Height of a box
      public void setLength( double len )
      {
         length = len;
      }

      public void setBreadth( double bre )
      {
         breadth = bre;
      }

      public void setHeight( double hei )
      {
         height = hei;
      }
      public double getVolume()
      {
         return length * breadth * height;
      }
   }
   class Boxtester
   {
      static void Main(string[] args)
      {
         Box Box1 = new Box();   // Declare Box1 of type Box
         Box Box2 = new Box();
         double volume;

         // Declare Box2 of type Box
         // box 1 specification
         Box1.setLength(6.0);
         Box1.setBreadth(7.0);
         Box1.setHeight(5.0);

         // box 2 specification
         Box2.setLength(12.0);
         Box2.setBreadth(13.0);
         Box2.setHeight(10.0);

         // volume of box 1
         volume = Box1.getVolume();
         Console.WriteLine("Volume of Box1 : {0}" ,volume);

         // volume of box 2
         volume = Box2.getVolume();
         Console.WriteLine("Volume of Box2 : {0}", volume);

         Console.ReadKey();
      }
   }
}

當(dāng)編譯和執(zhí)行上述代碼時,會產(chǎn)生以下結(jié)果:

Volume of Box1 : 210
Volume of Box2 : 1560

C# 構(gòu)造函數(shù)

類構(gòu)造函數(shù)是當(dāng)創(chuàng)建該類的新對象時執(zhí)行的一個類的特殊成員函數(shù)。

構(gòu)造函數(shù)具有與類完全相同的名稱,它沒有任何返回值。下面的例子解釋了構(gòu)造函數(shù)的概念:

using System;
namespace LineApplication
{
   class Line
   {
      private double length;   // Length of a line
      public Line()
      {
         Console.WriteLine("Object is being created");
      }

      public void setLength( double len )
      {
         length = len;
      }

      public double getLength()
      {
         return length;
      }

      static void Main(string[] args)
      {
         Line line = new Line();    

         // set line length
         line.setLength(6.0);
         Console.WriteLine("Length of line : {0}", line.getLength());
         Console.ReadKey();
      }
   }
}

當(dāng)編譯和執(zhí)行上述代碼時,會產(chǎn)生以下結(jié)果:

Object is being created
Length of line : 6

默認(rèn)構(gòu)造函數(shù)沒有任何參數(shù),但是如果需要,構(gòu)造函數(shù)可以有參數(shù)。這樣的構(gòu)造函數(shù)被稱為參數(shù)化構(gòu)造函數(shù)。此技術(shù)可用在創(chuàng)建時為對象分配初始值,如以下示例所示:

using System;
namespace LineApplication
{
   class Line
   {
      private double length;   // Length of a line
      public Line(double len)  //Parameterized constructor
      {
         Console.WriteLine("Object is being created, length = {0}", len);
         length = len;
      }

      public void setLength( double len )
      {
         length = len;
      }
      public double getLength()
      {
         return length;
      }

      static void Main(string[] args)
      {
         Line line = new Line(100.0);
         Console.WriteLine("Length of line : {0}", line.getLength()); 

         // set line length
         line.setLength(60.0);
         Console.WriteLine("Length of line : {0}", line.getLength()); 
         Console.ReadKey();
      }
   }
}

當(dāng)編譯和執(zhí)行上述代碼時,會產(chǎn)生以下結(jié)果:

Object is being created, length = 100
Length of line : 100
Length of line : 60

C# 析構(gòu)函數(shù)

析構(gòu)函數(shù)是一個類的特殊成員函數(shù),只要其類的對象超出范圍就執(zhí)行。析構(gòu)函數(shù)使用具有前綴波形符(~)和類名稱來表示,并且它不能擁有返回值,也不能使用任何參數(shù)。

析構(gòu)函數(shù)在退出程序之前釋放內(nèi)存資源非常有用。 析構(gòu)函數(shù)不能被繼承或重載。

以下示例解釋析構(gòu)函數(shù)的用法,參考代碼:

using System;
namespace LineApplication
{
   class Line
   {
      private double length;   // Length of a line
      public Line()  // constructor
      {
         Console.WriteLine("Object is being created");
      }
      ~Line() //destructor
      {
         Console.WriteLine("Object is being deleted");
      }

      public void setLength( double len )
      {
         length = len;
      }

      public double getLength()
      {
         return length;
      }

      static void Main(string[] args)
      {
         Line line = new Line();

         // set line length
         line.setLength(126.0);
         Console.WriteLine("Length of line : {0}", line.getLength());           
      }
   }
}

當(dāng)編譯和執(zhí)行上述代碼時,會產(chǎn)生以下結(jié)果:

Object is being created
Length of line : 126
Object is being deleted

C# 類靜態(tài)成員

我們可以使用static關(guān)鍵字將類成員定義為靜態(tài)(static)。 當(dāng)將一個類的成員聲明為靜態(tài)時,則無論創(chuàng)建了多少個類的對象,靜態(tài)成員只有一個副本。

在一個類使用關(guān)鍵字static來修辭成員,則表示實例只有一個成員存在。靜態(tài)變量用于定義常量,因為它們的值可以通過調(diào)用該類而不創(chuàng)建它的實例來引用。 靜態(tài)變量可以在成員函數(shù)或類定義之外初始化。還可以在類定義內(nèi)初始化靜態(tài)變量。

以下示例演示了如何使用靜態(tài)變量:

using System;
namespace StaticVarApplication
{
   class StaticVar
   {
      public static int num;
      public void count()
      {
         num++;
      }
      public int getNum()
      {
         return num;
      }
   }
   class StaticTester
   {
      static void Main(string[] args)
      {
         StaticVar s1 = new StaticVar();
         StaticVar s2 = new StaticVar();
         s1.count();
         s1.count();
         s1.count();
         s2.count();
         Console.WriteLine("Variable num for s1: {0}", s1.getNum());
         Console.WriteLine("Variable num for s2: {0}", s2.getNum());
         Console.ReadKey();
      }
   }
}

當(dāng)編譯和執(zhí)行上述代碼時,會產(chǎn)生以下結(jié)果:

Variable num for s1: 4
Variable num for s2: 4

您也可以將成員函數(shù)聲明為靜態(tài)。這些函數(shù)只能訪問靜態(tài)變量。靜態(tài)函數(shù)即使在創(chuàng)建對象之前也存在。以下示例演示了如何使用靜態(tài)函數(shù):

using System;
namespace StaticVarApplication
{
   class StaticVar
   {
      public static int num;
      public void count()
      {
         num++;
      }
      public static int getNum()
      {
         return num;
      }
   }
   class StaticTester
   {
      static void Main(string[] args)
      {
         StaticVar s = new StaticVar();
         s.count();
         s.count();
         s.count();
         Console.WriteLine("Variable num: {0}", StaticVar.getNum());
         Console.ReadKey();
      }
   }
}

當(dāng)編譯和執(zhí)行上述代碼時,會產(chǎn)生以下結(jié)果:

Variable num: 3

上一篇:C#多線程生命周期下一篇:C#反射