[英]Automatic properties
我想知道,當您創建一個Automatic屬性並在main()
方法中為一個隨機值調用set
,該value
存儲在哪里?
如本例所示:
class Program
{
static void Main(string[] args)
{
Example W = new Example();
W.Num = 10;
Console.WriteLine("{0}", W.Num);
Console.WriteLine("{0}", W.getNum());
}
}
class Example
{
private int num;
public int Num { get; set; }
public int getNum() { return num; }
}
為什么輸出:
10
0
因為您返回的是num
而不是Num
。 並且num
未初始化,因此該值為0。
這里沒有異常。
你打電話時
Example W = new Example();
然后最初的num = 0和Num = 0;
您分配了Num,而不是num。
您的Example
類中的num
是多余的。
如果您在將自動屬性初始化程序添加到c#之前編寫了此代碼,它將看起來像這樣:
private int num;
public int Num
{
get{ return num;}
set{ num = value;}
}
撰寫public public int Num { get; set; }
public int Num { get; set; }
public int Num { get; set; }
本質上是同一幕后的事物。 無需實現getNum()
(類似於Java),因為它等效於int a = w.Num;
。
當getter或setter不需要其他邏輯時,自動實現的屬性可使代碼更整潔。 編譯器實際上會為自動實現的屬性生成一個后備字段,但是該后備字段在您的代碼中不可見。
在您的示例中, num
字段和Num
屬性之間沒有任何聯系,因此沒有理由更改num
。
如果使用new
關鍵字,則您在類中創建了新實例,並重新創建了所有對象。
例如 ;
class Program
{
static void Main(string[] args)
{
Example W = new Example();
W.Num = 10;
Example W1 = new Example();
Console.WriteLine("{0}", W.Num); //10
Console.WriteLine("{0}", W1.Num); //0
}
}
這僅是您的答案的信息; 您返回不同的變量。 你沒有設置它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.