什么是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());
//设置线长
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
热门推荐
10 新年门口花束祝福语简短
11 盘锦结婚祝福语大全简短
12 父母生日祝福语 简短独特
13 家庭恩爱祝福语简短英文
14 高考俄语祝福语大全简短
15 虎年祝福语 诗句唯美简短
16 生日婚礼祝福语简短精辟
17 虎年喝酒拜年祝福语简短
18 教师闺蜜祝福语简短