我試圖更好地理解屬性,我通過這個例子遇到了這個頁面:
https://www.tutorialspoint.com/csharp/csharp_properties.htm
using System;
namespace tutorialspoint {
class Student {
private string code = "N.A";
private string name = "not known";
private int age = 0;
// Declare a Code property of type string:
public string Code {
get {
return code;
}
set {
code = value;
}
}
// Declare a Name property of type string:
public string Name {
get {
return name;
}
set {
name = value;
}
}
// Declare a Age property of type int:
public int Age {
get {
return age;
}
set {
age = value;
}
}
public override string ToString() {
return "Code = " Code ", Name = " Name ", Age = " Age;
}
}
class ExampleDemo {
public static void Main() {
// Create a new Student object:
Student s = new Student();
// Setting code, name and the age of the student
s.Code = "001";
s.Name = "Zara";
s.Age = 9;
Console.WriteLine("Student Info: {0}", s);
//let us increase age
s.Age = 1;
Console.WriteLine("Student Info: {0}", s);
Console.ReadKey();
}
}
}
輸出:學生資訊:代碼 = 001,姓名 = Zara,年齡 = 9
我不明白第一個示例如何能夠輸出寫在“學生”類中的整行。在 main 方法中,我們使用“s”,它是在“exampledemo”類中創建的物件。它如何能夠呼叫另一個類的方法?我猜這與繼承和多型性有關(我在 Google 上搜索了 override 關鍵字),但在我看來,這兩個類是獨立的,而不是另一個類的子類。我是編程的初學者,可能很困惑。
uj5u.com熱心網友回復:
s是型別Student(在 的第一行宣告Main())。因此,可以呼叫物件上的方法來修改或列印它。當你這樣做時, s.Name = "Zara";你已經在呼叫一個方法Student來更新它(從技術上講,方法和屬性是相同的,它們只是語法不同)。
該行Console.WriteLine("Student Info: {0}", s);實際上與 相同Console.WriteLine("Student Info: " s.ToString());。編譯器允許以更短的形式撰寫它,但在內部也會發生同樣的事情。
uj5u.com熱心網友回復:
讓我舉一個現實生活中的例子。
你有你夢想中的自行車的草圖。你的自行車只存在于草圖中。這是一堂課。
然后你要去車庫并從草圖中建造你的自行車。這個程序可以稱為在工廠從您的草圖創建自行車物件 。
根據您的示例, class 是Student.
您正在通過以下行創建一個物件:
Student s = new Student();
物件占用記憶體空間。我們如何從記憶體中讀取物件的值?通過使用物件參考。
s是對新創建的物件型別的物件參考Student。
它如何能夠呼叫另一個類的方法?
s是對新創建的物件型別的物件參考Student。所以它可以呼叫public這個物件的任何方法。
我試圖了解屬性
屬性是 getter 和 setter 方法的演變。在 C# 中尋找一個簡短的 getter/setter 示例
編譯器為一個屬性生成一對 get 和 set方法,以及一個用于自動實作的屬性的私有支持欄位。 C# 屬性實際上是方法嗎?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/476337.html
