如何在 C# 中例項化一個類?


使用 new 運算子在 C# 中例項化一個類。

假設我們的類是 Line。例項化將建立新的物件,如下所示:

Line line = new Line();

使用物件,你現在可以呼叫方法:

line.setLength(6.0);

讓我們看這個例子:

示例

 演示

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

輸出

Object is being created
Length of line : 6

更新於: 22-6 月 -2020

4K+ 瀏覽量

開啟您的事業

透過完成該課程獲取認證

立即開始
廣告