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