C# 程式中的建構函式是什麼?


類建構函式是每次我們建立該類的物件時執行的類的特殊成員函式。

建構函式與類具有完全相同的名字,並且沒有返回型別。

建構函式具有與類名完全相同的名字 −

class Demo {

   public Demo() {}
}

以下是一個示例 −

示例

 線上演示

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();
      }
   }
}

輸出

Object is being created
Length of line : 6

更新日期: 20-Jun-2020

480 次瀏覽

助力您的職業生涯 生涯

結業課程獲得認證

立即開始
廣告
© . All rights reserved.