c#教程第十课:属性
文章来源:互联网
本节课将介绍c#的属性,其目的包括:
1.理解什么是属性
2.如何实现属性
3.创建一个只读属性
4.创建一个只写属性
属性是c#中独具特色的新功能。通过属性来读写类中的域,这具有一定的保护功能。在其它语言中,这是通过实现特定的getter和setter方法来实现的。C#的属性具有保护功能,可以让你就象访问域一样访问属性。要了解属性的用法,我们先来看看如何用传统的方法对域进行封装。
1.清单 10-1. 传统的访问类的域的例子:Accessors.cs |
using System; public class PropertyHolder { private int someProperty = 0; public int getSomeProperty() { return someProperty; } public void setSomeProperty(int propValue) { someProperty = propValue; } } public class PropertyTester { public static int Main(string[] args) { PropertyHolder propHold = new PropertyHolder(); propHold.setSomeProperty(5); Console.WriteLine("Property Value: {0}", propHold.getSomeProperty()); return 0; } } |
说明 |
2.清单 10-2. 使用属性访问类的域:Properties.cs |
using System; public class PropertyHolder { private int someProperty = 0; public int SomeProperty { get { return someProperty; } set { someProperty = value; } } } public class PropertyTester { public static int Main(string[] args) { PropertyHolder propHold = new PropertyHolder(); propHold.SomeProperty = 5; Console.WriteLine("Property Value: {0}", propHold.SomeProperty); return 0; } } |
说明 |
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; } } |
说明 |
4.清单 10-4. 只写属性: WriteOnlyProperty.cs |
using System; public class PropertyHolder { private int someProperty = 0; public int SomeProperty { set { someProperty = value; Console.WriteLine("someProperty is equal to {0}", someProperty); } } } public class PropertyTester { public static int Main(string[] args) { PropertyHolder propHold = new PropertyHolder(); propHold.SomeProperty = 5; return 0; } } |
说明 |
文章评论(0条评论)
登录后参与讨论