属性提供了灵活的机制,读写那些私有字段的值。通过属性访问数据,可以大大增强数据访问的安全性和灵活性。通过属性访问器,可以设置成只读,只写或读写。
C#通过get关键字来设置只读的
private string test;
public string Test
{
get
{
return test;
}
}
属性Test配合私有变量test一起使用,通过get关键获得属性访问器Test的值。
通过set关键字来设置可写的,
private string test;
public string Test
{
set
{
test = value;
}
}
调用
static void Main(string[] args)
{
Laptop laptop = new Laptop();
laptop.Test = "helll":
Console.WriteLine(laptop.Test);
}