打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
C# Property机制

可以把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 CustomerManagerWithAccessorMethods31 {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         get10         {11             return m_id;12         }13         set14         {15             m_id = value;16         }17     }18 19     private string m_name = string.Empty;20 21     public string Name22     {23         get24         {25             return m_name;26         }27         set28         {29             m_name = value;30         }31     }32 }33 34 public class CustomerManagerWithProperties35 {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();
    }
}

  

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
apiCode/1/1.1/1.1.1
base 关键字
JPA标注
C# 属性(Property) | 菜鸟教程
使用jaxb将XML转化为JAVA BEAN
Struts2、Spring和Hibernate应用实例
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服