2.PropertyTester 类使用PropertyHolder类中的SomeProperty属性。
在Main方法的第一行中, 创建了PropertyHolder对象propHold。之后,把propHold对象的 someProperty 域的值设置为5,很简单,就象对域赋值一样,给属性赋值。
3.Console.WriteLine方法输出 propHold对象的someProperty域的值。
这是通过使用propHold对象的SomeProperty属性来完成的。很简单,就象对域赋值一样,赋值给属性。属性可以设置为只读的,这可以通过在属性的实现中只设一个get访问符号来实现。
| 3.清单 10-3. 只读属性: ReadOnlyProperty.cs |
| using System; public class PropertyHolder { private int someProperty = 0; public PropertyHolder(int propVal) { someProperty = propVal; } public int SomeProperty { get { return someProperty; } } } public class PropertyTester { public static int Main(string[] args) { PropertyHolder propHold = new PropertyHolder(5); Console.WriteLine("Property Value: {0}", propHold.SomeProperty); return 0; } } |
| 说明 |
1.清单10-3 演示了如何实现只读属性。
PropertyHolder类中,SomeProperty 属性只有一个get访问操作,没有用到set访问操作。PropertyHolder类中还有个接受整型参数的构造函数。