如何在 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
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP