舉例講解C#中自動(dòng)實(shí)現(xiàn)的屬性
在 C# 3.0 及更高版本,當(dāng)屬性訪問器中不需要任何其他邏輯時(shí),自動(dòng)實(shí)現(xiàn)的屬性會(huì)使屬性聲明更加簡(jiǎn)潔。它們還允許客戶端代碼創(chuàng)建對(duì)象。當(dāng)你聲明以下示例中所示的屬性時(shí),編譯器將創(chuàng)建僅可以通過該屬性的 get 和 set 訪問器訪問的專用、匿名支持字段。
下列示例演示一個(gè)簡(jiǎn)單的類,它具有某些自動(dòng)實(shí)現(xiàn)的屬性:
// This class is mutable. Its data can be modified from // outside the class. class Customer { // Auto-Impl Properties for trivial get and set public double TotalPurchases { get; set; } public string Name { get; set; } public int CustomerID { get; set; } // Constructor public Customer(double purchases, string name, int ID) { TotalPurchases = purchases; Name = name; CustomerID = ID; } // Methods public string GetContactInfo() {return "ContactInfo";} public string GetTransactionHistory() {return "History";} // .. Additional methods, events, etc. } class Program { static void Main() { // Intialize a new object. Customer cust1 = new Customer ( 4987.63, "Northwind",90108 ); //Modify a property cust1.TotalPurchases += 499.99; } }
在 C# 6 和更高版本中,你可以像字段一樣初始化自動(dòng)實(shí)現(xiàn)屬性:
public string FirstName { get; set; } = "Jane";
上一示例中所示的類是可變的。創(chuàng)建客戶端代碼后可以用于更改對(duì)象中的值。在包含重要行為(方法)以及數(shù)據(jù)的復(fù)雜類中,通常有必要具有公共屬性。但是,對(duì)于較小類或僅封裝一組值(數(shù)據(jù))且只有很少行為或沒有行為的結(jié)構(gòu),則應(yīng)該通過聲明 set 訪問器為 專用(對(duì)使用者的不可變)或通過聲明僅一個(gè) get 訪問器 (除構(gòu)造函數(shù)外都不可變),使對(duì)象不可變。
動(dòng)實(shí)現(xiàn)的屬性上允許使用特性,但很明顯支持字段上不允許,因?yàn)椴荒軓哪愕脑创a訪問它們。如果必須使用屬性的支持字段上的特性,只需創(chuàng)建一個(gè)常規(guī)屬性。
使用自動(dòng)實(shí)現(xiàn)的屬性實(shí)現(xiàn)輕量類
本示例演示如何創(chuàng)建一個(gè)僅用于封裝一組自動(dòng)實(shí)現(xiàn)的屬性的不可變輕型類。 當(dāng)你必須使用引用類型語義時(shí),請(qǐng)使用此種構(gòu)造而不是結(jié)構(gòu)。
可通過兩種方法來實(shí)現(xiàn)不可變的屬性。 可以將 set 取值函數(shù)聲明為 private。 屬性只能在該類型中設(shè)置,但它對(duì)于使用者是不可變的。 也可以僅聲明 get 取值函數(shù),使屬性除了能在該類型的構(gòu)造函數(shù)中設(shè)置,在其他任何位置都不可變。
當(dāng)你聲明一個(gè) private set 取值函數(shù)時(shí),你無法使用對(duì)象初始值設(shè)定項(xiàng)來初始化屬性。 你必須使用構(gòu)造函數(shù)或工廠方法。
示例
下面的示例演示了實(shí)現(xiàn)具有自動(dòng)實(shí)現(xiàn)屬性的不可變類的兩種方法。 這兩種方法均使用 private set 聲明其中一個(gè)屬性,使用單獨(dú)的 get 聲明另一個(gè)屬性。 第一個(gè)類僅使用構(gòu)造函數(shù)來初始化屬性,第二個(gè)類則使用可調(diào)用構(gòu)造函數(shù)的靜態(tài)工廠方法。
// This class is immutable. After an object is created, // it cannot be modified from outside the class. It uses a // constructor to initialize its properties. class Contact { // Read-only properties. public string Name { get; } public string Address { get; private set; } // Public constructor. public Contact(string contactName, string contactAddress) { Name = contactName; Address = contactAddress; } } // This class is immutable. After an object is created, // it cannot be modified from outside the class. It uses a // static method and private constructor to initialize its properties. public class Contact2 { // Read-only properties. public string Name { get; private set; } public string Address { get; } // Private constructor. private Contact2(string contactName, string contactAddress) { Name = contactName; Address = contactAddress; } // Public factory method. public static Contact2 CreateContact(string name, string address) { return new Contact2(name, address); } } public class Program { static void Main() { // Some simple data sources. string[] names = {"Terry Adams","Fadi Fakhouri", "Hanying Feng", "Cesar Garcia", "Debra Garcia"}; string[] addresses = {"123 Main St.", "345 Cypress Ave.", "678 1st Ave", "12 108th St.", "89 E. 42nd St."}; // Simple query to demonstrate object creation in select clause. // Create Contact objects by using a constructor. var query1 = from i in Enumerable.Range(0, 5) select new Contact(names[i], addresses[i]); // List elements cannot be modified by client code. var list = query1.ToList(); foreach (var contact in list) { Console.WriteLine("{0}, {1}", contact.Name, contact.Address); } // Create Contact2 objects by using a static factory method. var query2 = from i in Enumerable.Range(0, 5) select Contact2.CreateContact(names[i], addresses[i]); // Console output is identical to query1. var list2 = query2.ToList(); // List elements cannot be modified by client code. // CS0272: // list2[0].Name = "Eugene Zabokritski"; // Keep the console open in debug mode. Console.WriteLine("Press any key to exit."); Console.ReadKey(); } }
輸出:
Terry Adams, 123 Main St. Fadi Fakhouri, 345 Cypress Ave. Hanying Feng, 678 1st Ave Cesar Garcia, 12 108th St. Debra Garcia, 89 E. 42nd St.
編譯器為每個(gè)自動(dòng)實(shí)現(xiàn)的屬性創(chuàng)建了支持字段。 這些字段無法直接從源代碼進(jìn)行訪問。
上一篇:詳解C#中的屬性和屬性的使用
欄 目:C#教程
本文標(biāo)題:舉例講解C#中自動(dòng)實(shí)現(xiàn)的屬性
本文地址:http://mengdiqiu.com.cn/a1/C_jiaocheng/6743.html
您可能感興趣的文章
- 01-10C#通過反射獲取當(dāng)前工程中所有窗體并打開的方法
- 01-10C#實(shí)現(xiàn)Winform中打開網(wǎng)頁頁面的方法
- 01-10C#實(shí)現(xiàn)由四周向中心縮小的窗體退出特效
- 01-10Extjs4如何處理后臺(tái)json數(shù)據(jù)中日期和時(shí)間
- 01-10C#中DataGridView常用操作實(shí)例小結(jié)
- 01-10C#編程獲取資源文件中圖片的方法
- 01-10asp.net中XML如何做增刪改查操作
- 01-10C#利用反射技術(shù)實(shí)現(xiàn)去掉按鈕選中時(shí)的邊框效果
- 01-10C#中查找Dictionary中的重復(fù)值的方法
- 01-10C#中TreeView實(shí)現(xiàn)適合兩級(jí)節(jié)點(diǎn)的選中節(jié)點(diǎn)方法


閱讀排行
- 1C語言 while語句的用法詳解
- 2java 實(shí)現(xiàn)簡(jiǎn)單圣誕樹的示例代碼(圣誕
- 3利用C語言實(shí)現(xiàn)“百馬百擔(dān)”問題方法
- 4C語言中計(jì)算正弦的相關(guān)函數(shù)總結(jié)
- 5c語言計(jì)算三角形面積代碼
- 6什么是 WSH(腳本宿主)的詳細(xì)解釋
- 7C++ 中隨機(jī)函數(shù)random函數(shù)的使用方法
- 8正則表達(dá)式匹配各種特殊字符
- 9C語言十進(jìn)制轉(zhuǎn)二進(jìn)制代碼實(shí)例
- 10C語言查找數(shù)組里數(shù)字重復(fù)次數(shù)的方法
本欄相關(guān)
- 01-10C#通過反射獲取當(dāng)前工程中所有窗體并
- 01-10關(guān)于ASP網(wǎng)頁無法打開的解決方案
- 01-10WinForm限制窗體不能移到屏幕外的方法
- 01-10WinForm繪制圓角的方法
- 01-10C#實(shí)現(xiàn)txt定位指定行完整實(shí)例
- 01-10WinForm實(shí)現(xiàn)仿視頻 器左下角滾動(dòng)新
- 01-10C#停止線程的方法
- 01-10C#實(shí)現(xiàn)清空回收站的方法
- 01-10C#通過重寫Panel改變邊框顏色與寬度的
- 01-10C#實(shí)現(xiàn)讀取注冊(cè)表監(jiān)控當(dāng)前操作系統(tǒng)已
隨機(jī)閱讀
- 04-02jquery與jsp,用jquery
- 01-11ajax實(shí)現(xiàn)頁面的局部加載
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 01-10使用C語言求解撲克牌的順子及n個(gè)骰子
- 01-10C#中split用法實(shí)例總結(jié)
- 08-05織夢(mèng)dedecms什么時(shí)候用欄目交叉功能?
- 08-05dedecms(織夢(mèng))副欄目數(shù)量限制代碼修改
- 01-10delphi制作wav文件的方法
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
- 08-05DEDE織夢(mèng)data目錄下的sessions文件夾有什