如何在 C# 中实例化一个类?

csharpprogrammingserver side programming更新于 2025/5/25 9:52:17

在 C# 中使用 new 运算符实例化一个类。

假设我们的类是 Line。实例化将创建一个新对象,如下所示:−

Line line = new Line();

现在可以使用该对象调用方法 −

line.setLength(6.0);

我们来看一个示例 −

示例

using System;

namespace LineApplication {
   class Line {
      private double length; // 线的长度

      public Line() {
         Console.WriteLine("正在创建对象");
      }
      public void setLength( double len ) {
         length = len;
      }
      public double getLength() {
         return length;
      }

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

          // 设置行长度
         line.setLength(6.0);
         Console.WriteLine("Length of line : {0}", line.getLength());
      }
   }
}

输出

Object is being created
Length of line : 6

相关文章