- 先上声明一个类的代码
public class MyClass
{
// this is a field. It is private to your class and stores the actual data.
private string _myField;
// this is a property. When you access it uses the underlying field, but only exposes
// the contract that will not be affected by the underlying field
public string MyField
{
get
{
return _myField;
}
set
{
_myField = value;
}
}
}
- 然后是调用的代码,get和set其实就是重载了等号
MyClass myc;
string input="input";
myc.MyField=input;
string output=myc.MyField;
- 也可以增加在set里面增加一些判断
class Bank
{
private int money;//私有字段
public int Money //属性
{
get { return money; }
//增加限制,存钱不能为负数
set
{
if (value >= 0) {
money = value;
}
else {
money = 0;
}
}
}
}