使用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(); //设置线长 line.setLength(6.0); Console.WriteLine("Length of line : {0}", line.getLength()); } } }
输出结果
Object is being created Length of line : 6