可以把C#的property机制看成是C#在语言层面上对数据的封装。
在使用Property时,可以把它当做一个Field使用。
传统的C++中使用的方法类似于:
1 using System; 2 3 public class Customer 4 { 5 private int m_id = -1; 6 7 public int GetID() 8 { 9 return m_id; 10 } 11 12 public void SetID(int id) 13 { 14 m_id = id; 15 } 16 17 private string m_name = string.Empty; 18 19 public string GetName() 20 { 21 return m_name; 22 } 23 24 public void SetName(string name) 25 { 26 m_name = name; 27 } 28 } 29 30 public class CustomerManagerWithAccessorMethods 31 { 32 public static void Main() 33 { 34 Customer cust = new Customer(); 35 36 cust.SetID(1); 37 cust.SetName("Amelio Rosales"); 38 39 Console.WriteLine( 40 "ID: {0}, Name: {1}", 41 cust.GetID(), 42 cust.GetName()); 43 44 Console.ReadKey(); 45 } 46 }
而使用property的方法为:
1 using System; 2 3 public class Customer 4 { 5 private int m_id = -1; 6 7 public int ID 8 { 9 get 10 { 11 return m_id; 12 } 13 set 14 { 15 m_id = value; 16 } 17 } 18 19 private string m_name = string.Empty; 20 21 public string Name 22 { 23 get 24 { 25 return m_name; 26 } 27 set 28 { 29 m_name = value; 30 } 31 } 32 } 33 34 public class CustomerManagerWithProperties 35 { 36 public static void Main() 37 { 38 Customer cust = new Customer(); 39 40 cust.ID = 1; 41 cust.Name = "Amelio Rosales"; 42 43 Console.WriteLine( 44 "ID: {0}, Name: {1}", 45 cust.ID, 46 cust.Name); 47 48 Console.ReadKey(); 49 } 50 }
这在一定程度上实现了封装与数据隐藏。
不设set方法即可将一个field视为只读,不设get方法即可将一个field视为只写。
这样做的一个问题是,如果一个类有很多成员变量,设置get,set就会变得繁琐,因此C# 3.0引入了 Auto-Implemented Properties机制。
使用方法如下:
using System; public class Customer { public int ID { get; set; } public string Name { get; set; } } public class AutoImplementedCustomerManager { static void Main() { Customer cust = new Customer(); cust.ID = 1; cust.Name = "Amelio Rosales"; Console.WriteLine( "ID: {0}, Name: {1}", cust.ID, cust.Name); Console.ReadKey(); } }