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


類建構函式是一個類的特殊成員函式,每當我們建立該類的物件時便會執行此函式。預設建構函式沒有任何引數。

以下是一個展示如何在 C# 中使用預設建構函式的示例 -

示例

 即時演示

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(10.0);
         Console.WriteLine("Length of line : {0}", line.getLength());

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

輸出

Object is being created, length = 10
Length of line : 10
Length of line : 6

更新於: 20-Jun-2020

195 次瀏覽

開拓你的 事業

完成課程以獲得認證

開始
廣告
© . All rights reserved.