舉例講解C#中自動(dòng)實(shí)現(xiàn)的屬性
在 C# 3.0 及更高版本,當(dāng)屬性訪問(wèn)器中不需要任何其他邏輯時(shí),自動(dòng)實(shí)現(xiàn)的屬性會(huì)使屬性聲明更加簡(jiǎn)潔。它們還允許客戶(hù)端代碼創(chuàng)建對(duì)象。當(dāng)你聲明以下示例中所示的屬性時(shí),編譯器將創(chuàng)建僅可以通過(guò)該屬性的 get 和 set 訪問(wèn)器訪問(wèn)的專(zhuān)用、匿名支持字段。
下列示例演示一個(gè)簡(jiǎn)單的類(lèi),它具有某些自動(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";
上一示例中所示的類(lèi)是可變的。創(chuàng)建客戶(hù)端代碼后可以用于更改對(duì)象中的值。在包含重要行為(方法)以及數(shù)據(jù)的復(fù)雜類(lèi)中,通常有必要具有公共屬性。但是,對(duì)于較小類(lèi)或僅封裝一組值(數(shù)據(jù))且只有很少行為或沒(méi)有行為的結(jié)構(gòu),則應(yīng)該通過(guò)聲明 set 訪問(wèn)器為 專(zhuān)用(對(duì)使用者的不可變)或通過(guò)聲明僅一個(gè) get 訪問(wèn)器 (除構(gòu)造函數(shù)外都不可變),使對(duì)象不可變。
動(dòng)實(shí)現(xiàn)的屬性上允許使用特性,但很明顯支持字段上不允許,因?yàn)椴荒軓哪愕脑创a訪問(wèn)它們。如果必須使用屬性的支持字段上的特性,只需創(chuàng)建一個(gè)常規(guī)屬性。
使用自動(dòng)實(shí)現(xiàn)的屬性實(shí)現(xiàn)輕量類(lèi)
本示例演示如何創(chuàng)建一個(gè)僅用于封裝一組自動(dòng)實(shí)現(xiàn)的屬性的不可變輕型類(lèi)。 當(dāng)你必須使用引用類(lèi)型語(yǔ)義時(shí),請(qǐng)使用此種構(gòu)造而不是結(jié)構(gòu)。
可通過(guò)兩種方法來(lái)實(shí)現(xiàn)不可變的屬性。 可以將 set 取值函數(shù)聲明為 private。 屬性只能在該類(lèi)型中設(shè)置,但它對(duì)于使用者是不可變的。 也可以?xún)H聲明 get 取值函數(shù),使屬性除了能在該類(lèi)型的構(gòu)造函數(shù)中設(shè)置,在其他任何位置都不可變。
當(dāng)你聲明一個(gè) private set 取值函數(shù)時(shí),你無(wú)法使用對(duì)象初始值設(shè)定項(xiàng)來(lái)初始化屬性。 你必須使用構(gòu)造函數(shù)或工廠方法。
示例
下面的示例演示了實(shí)現(xiàn)具有自動(dòng)實(shí)現(xiàn)屬性的不可變類(lèi)的兩種方法。 這兩種方法均使用 private set 聲明其中一個(gè)屬性,使用單獨(dú)的 get 聲明另一個(gè)屬性。 第一個(gè)類(lèi)僅使用構(gòu)造函數(shù)來(lái)初始化屬性,第二個(gè)類(lèi)則使用可調(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)建了支持字段。 這些字段無(wú)法直接從源代碼進(jìn)行訪問(wèn)。
- C#中使用反射遍歷一個(gè)對(duì)象屬性及值的小技巧
- C#使用shell32獲取文件屬性的方法
- C#使用Directoryinfo類(lèi)獲得目錄信息和屬性的方法
- C#多線程之Thread中Thread.IsAlive屬性用法分析
- C#實(shí)現(xiàn)ProperTyGrid自定義屬性的方法
- C#屬性(Attribute)用法實(shí)例解析
- C#利用反射來(lái)判斷對(duì)象是否包含某個(gè)屬性的實(shí)現(xiàn)方法
- C#關(guān)于類(lèi)的只讀只寫(xiě)屬性實(shí)例分析
- C#正則表達(dá)式獲取下拉菜單(select)的相關(guān)屬性值
- C#類(lèi)中的屬性使用總結(jié)(詳解類(lèi)的屬性)
- C#類(lèi)中屬性與成員變量的使用小結(jié)
- C#中屬性和成員變量的區(qū)別說(shuō)明
相關(guān)文章
基于C#實(shí)現(xiàn)的HOOK鍵盤(pán)鉤子實(shí)例代碼
這篇文章主要介紹了基于C#實(shí)現(xiàn)的HOOK鍵盤(pán)鉤子實(shí)例,需要的朋友可以參考下2014-07-07C#/VB.NET 實(shí)現(xiàn)在PDF表格中添加條形碼
條碼的應(yīng)用已深入生活和工作的方方面面。在處理?xiàng)l碼時(shí),常需要和各種文檔格式相結(jié)合。本文,以操作PDF文件為例,介紹如何在編輯表格時(shí),向單元格中插入條形碼,需要的可以參考一下2022-06-06WinForm實(shí)現(xiàn)同時(shí)讓兩個(gè)窗體有激活效果的特效實(shí)例
這篇文章主要介紹了WinForm實(shí)現(xiàn)同時(shí)讓兩個(gè)窗體有激活效果的特效實(shí)例,基于windows api實(shí)現(xiàn)一個(gè)窗體激活的時(shí)候給另外一個(gè)發(fā)消息的特效,在進(jìn)行C#項(xiàng)目開(kāi)發(fā)時(shí)有一定的實(shí)用價(jià)值,需要的朋友可以參考下2014-09-09C#實(shí)現(xiàn)Winform無(wú)邊框移動(dòng)的方法
這篇文章主要介紹了C#實(shí)現(xiàn)Winform無(wú)邊框移動(dòng)的方法,涉及C#針對(duì)WinForm窗口操作的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-09-09.NET使用IResourceMonitor實(shí)現(xiàn)獲取資源信息
在 Microsoft.Extensions.Diagnostics.ResourceMonitoring 包提供了一系列定制 API,專(zhuān)用于監(jiān)視 .NET 應(yīng)用程序的資源利用率,本文將利用IResourceMonitor來(lái)實(shí)現(xiàn)獲取資源狀態(tài)信息,感興趣的可以了解下2024-01-01經(jīng)典排序算法之冒泡排序(Bubble sort)代碼
這篇文章主要介紹了經(jīng)典排序算法之冒泡排序(Bubble sort)代碼的相關(guān)資料,非常不錯(cuò)具有參考借鑒價(jià)值,需要的朋友可以參考下2016-06-06