How to use "get" and "set" in c#?

2007-09-10 6:55 am
How to use "get" and "set" in c#?

回答 (1)

2007-09-10 5:41 pm
✔ 最佳答案
get and set are used to let the property of a class to be read and changed. If you want the property to be readable, use get. If you also want the property to be editable, use set.
Example:
public class Creature
{
private int limbs;
public Creature()
{
// constructor
}
public int Legs // Legs is the public property of Creature
{
get
{
// allow legs to be read
return limbs;
}
set
{
// allow legs to be changed
limbs = value;
}
}
}
// codes in the program
Creature dog = new Creature(); // create a new Creature
dog.Legs = 4; // call set
int x = dog.Legs; // call get
If the property is read-only, do not write the set part in the class.


收錄日期: 2021-04-25 20:32:50
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20070909000051KK05575

檢視 Wayback Machine 備份