C#入门
属性
属性概述
相关章节
属性是这样的成员:它们提供灵活的机制来读取、编写或计算私有字段的值。可以像使用公共数据成员一样使用属性,但实际上它们是称为“访问器”的特殊方法。这使得数据在可被轻松访问的同时,仍能提供方法的安全性和灵活性。
在本示例中,类 TimePeriod 存储了一个时间段。类内部以秒为单位存储时间,但提供一个称为 Hours 的属性,它允许客户端指定以小时为单位的时间。Hours 属性的访问器执行小时和秒之间的转换。
1
class TimePeriod
2
{
3
private double seconds;
4
5
public double Hours
6
{
7
get { return seconds / 3600; }
8
set { seconds = value * 3600; }
9
}
10
}
11
12
class Program
13
{
14
static void Main()
15
{
16
TimePeriod t = new TimePeriod();
17
18
// Assigning the Hours property causes the 'set' accessor to be called.
19
t.Hours = 24;
20
21
// Evaluating the Hours property causes the 'get' accessor to be called.
22
System.Console.WriteLine("Time in hours: " + t.Hours);
23
}
24
}
class TimePeriod2
{3
private double seconds;4

5
public double Hours6
{7
get { return seconds / 3600; }8
set { seconds = value * 3600; }9
}10
}11

12
class Program13
{14
static void Main()15
{16
TimePeriod t = new TimePeriod();17

18
// Assigning the Hours property causes the 'set' accessor to be called.19
t.Hours = 24;20

21
// Evaluating the Hours property causes the 'get' accessor to be called.22
System.Console.WriteLine("Time in hours: " + t.Hours);23
}24
}
输出
Time in hours: 24
属性概述
属性使类能够以一种公开的方法获取和设置值,同时隐藏实现或验证代码。
get 属性访问器用于返回属性值,而 set 访问器用于分配新值。这些访问器可以有不同的访问级别。有关更多信息,请参见访问器可访问性。
value 关键字用于定义由 set 索引器分配的值。
不实现 set 方法的属性是只读的。
相关章节
微信号:jamesworkshop 学习QQ群:364976091


浙公网安备 33010602011771号