分享

C# Property机制

 goodwangLib 2013-12-22

可以把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机制。

使用方法如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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();
    }
}

  

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多