2012-10-07 48 views
1

您好我最近開始學習C#並且有一些關於屬性的問題。 比方說,我有這樣的說法:在C中使用屬性獲取和注入字段#

private int minAge { get; set; } 

這是否翻譯成這樣:

private int minAge 

public int MinAge 
{ 
    get { return this.minAge; } 
    set { this.minAge = Convert.ToInt16(TextBox1.Text); } //this is what I would like      to set the field to 
} 

比方說,我有一個按鈕,當我按下那個按鈕,我需要它來設置MINAGE場之後返回數據。我可以如何實現這一目標?

我試過,但它似乎不工作:

minAge.get //to return data 
    minAge.set = Convert.ToInt16(TextBox1.Text); //to set the data 

回答

1

你只是要公開你的屬性:

public int minAge { get; set; } 

然後你就可以使用get和set(隱含):

int age = minAge; //to return data 
minAge = Convert.ToInt32(TextBox1.Text); //to set the data 
+0

我試着按照你說的方式去做:public int minAge {get;組; },minAge = 10; int a = minAge.get;但我得到一個erorr SAIS INT不包含定義獲取 – user1525474

+0

@ user1525474:編輯代碼 –

+0

okk因此換句話說C#自動調用get和set方法?我只需要一個確認,以瞭解如果我udnerstand這個權利 – user1525474

2

您定義的類裏面你的財產,以獲取和設置屬性,你必須使用類的實例

YourClass objYourClass = new objYourClass; 
int minAge= objYourClass.MinAge; //To get 

objYourClass.MinAge =Convert.ToInt16(TextBox1.Text); //o set the property 
+0

嗯所以我已經聲明一個對象,即使我在同一個類中使用它,我聲明它? – user1525474

1

該物業的設置和獲得與下劃線成員相同的類型...

private int minAge 

public int MinAge 
{ 
    get { return this.minAge; } 
    set { this.minAge = value } //"value" is of type int 
} 
2

您可以通過設置屬性:

minAge = 10; 

要檢索你可以做的屬性:

int age = minAge; // retrieves the age via the minAge property 

注意這個必須是Class此屬性定義裏面如果你試圖設置MINAGE的一個對象,你可以這樣做值:

var obj = new YourClass(); 

obj.minAge = 100; // sets minAge to 100 

int minAge = obj.minAge; // Assigns the minAge variable to that of `obj` minAge value. 

的差異

public int minAge { get; set; } 

之間

private int minAge 

public int MinAge 
{ 
    get { return this.minAge; } 
    set { this.minAge = Convert.ToInt16(TextBox1.Text); } //this is what I would like      to set the field to 

}

那是MINAGE使用輔助性質MinAge如果您使用的是.NET框架(4+)的最新版本之一,則不再需要它。

+0

所以換句話說,當我設置minAge = 10和int age = minAge C#自動調用屬性get和set? – user1525474

1

如果設置在C#中的屬性,你不必訪問GET和SET,它會自動完成:

// Get 
int age = this.MinAge; 

// Set 
this.MinAge = Convert.ToInt16(TextBox1.Text); 

您可以創建這樣的性質:

private int _minAge 

public int MinAge 
{ 
    get { return _minAge; } 
    set { _minAge = value; } 
} 

或者,如果你使用.NET 3。5或以上,您可以簡單使用:

public int MinAge 
{ 
    get; 
    set; 
} 

下拉類型由編譯器自動創建。

1

其實

public int MinAge { get; set; } 

由編譯器翻譯成像在C#

private int minAge_backfield; 

public int MinAge 
{ 
get { return minAge__backingField;} 
set { minAge__backingField = value;} 
} 

這就是所謂的汽車性能和它的使用及其簡單的像

var val = MinAge; 

MinAge = 10; 

我寫了一個blog post就可以了。