C#程序中的参数化构造函数是什么?
在构造函数中,你还可以添加参数。这种构造函数称为参数化构造函数。这种技术可以帮助你创建对象时给它分配初始值。
以下是一个示例 −
// class class Demo
带参数ランク的参数化构造函数 −
public Demo(int rank) {
Console.WriteLine("RANK = {0}", rank);
}以下是完整的示例,展示了如何在 C# 中使用参数化构造函数 −
示例
using System;
namespace Demo {
class Line {
private double length; // Length of a line
public Line(double len) { //Parameterized constructor
Console.WriteLine("Object is being created, length = {0}", len);
length = len;
}
public void setLength( double len ) {
length = len;
}
public double getLength() {
return length;
}
static void Main(string[] args) {
Line line = new Line(10.0);
Console.WriteLine("Length of line : {0}", line.getLength());
// set line length
line.setLength(6.0);
Console.WriteLine("Length of line : {0}", line.getLength());
Console.ReadKey();
}
}
}输出
Object is being created, length = 10 Length of line : 10 Length of line : 6
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
Javascript
PHP