C# 程序中的构造函数是什么?

csharpprogrammingserver side programming更新于 2025/9/26 9:07:17

类构造函数是类的一个特殊成员函数,每当我们创建该类的新对象时都会执行它。

构造函数的名称与类的名称完全相同,并且没有任何返回类型。

构造函数的名称与类名相同 −

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

相关文章