舉例講解C#中自動實現(xiàn)的屬性
在 C# 3.0 及更高版本,當屬性訪問器中不需要任何其他邏輯時,自動實現(xiàn)的屬性會使屬性聲明更加簡潔。它們還允許客戶端代碼創(chuàng)建對象。當你聲明以下示例中所示的屬性時,編譯器將創(chuàng)建僅可以通過該屬性的 get 和 set 訪問器訪問的專用、匿名支持字段。
下列示例演示一個簡單的類,它具有某些自動實現(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 和更高版本中,你可以像字段一樣初始化自動實現(xiàn)屬性:
public string FirstName { get; set; } = "Jane";
上一示例中所示的類是可變的。創(chuàng)建客戶端代碼后可以用于更改對象中的值。在包含重要行為(方法)以及數(shù)據(jù)的復(fù)雜類中,通常有必要具有公共屬性。但是,對于較小類或僅封裝一組值(數(shù)據(jù))且只有很少行為或沒有行為的結(jié)構(gòu),則應(yīng)該通過聲明 set 訪問器為 專用(對使用者的不可變)或通過聲明僅一個 get 訪問器 (除構(gòu)造函數(shù)外都不可變),使對象不可變。
動實現(xiàn)的屬性上允許使用特性,但很明顯支持字段上不允許,因為不能從你的源代碼訪問它們。如果必須使用屬性的支持字段上的特性,只需創(chuàng)建一個常規(guī)屬性。
使用自動實現(xiàn)的屬性實現(xiàn)輕量類
本示例演示如何創(chuàng)建一個僅用于封裝一組自動實現(xiàn)的屬性的不可變輕型類。 當你必須使用引用類型語義時,請使用此種構(gòu)造而不是結(jié)構(gòu)。
可通過兩種方法來實現(xiàn)不可變的屬性。 可以將 set 取值函數(shù)聲明為 private。 屬性只能在該類型中設(shè)置,但它對于使用者是不可變的。 也可以僅聲明 get 取值函數(shù),使屬性除了能在該類型的構(gòu)造函數(shù)中設(shè)置,在其他任何位置都不可變。
當你聲明一個 private set 取值函數(shù)時,你無法使用對象初始值設(shè)定項來初始化屬性。 你必須使用構(gòu)造函數(shù)或工廠方法。
示例
下面的示例演示了實現(xiàn)具有自動實現(xiàn)屬性的不可變類的兩種方法。 這兩種方法均使用 private set 聲明其中一個屬性,使用單獨的 get 聲明另一個屬性。 第一個類僅使用構(gòu)造函數(shù)來初始化屬性,第二個類則使用可調(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.
編譯器為每個自動實現(xiàn)的屬性創(chuàng)建了支持字段。 這些字段無法直接從源代碼進行訪問。
- C#中使用反射遍歷一個對象屬性及值的小技巧
- C#使用shell32獲取文件屬性的方法
- C#使用Directoryinfo類獲得目錄信息和屬性的方法
- C#多線程之Thread中Thread.IsAlive屬性用法分析
- C#實現(xiàn)ProperTyGrid自定義屬性的方法
- C#屬性(Attribute)用法實例解析
- C#利用反射來判斷對象是否包含某個屬性的實現(xiàn)方法
- C#關(guān)于類的只讀只寫屬性實例分析
- C#正則表達式獲取下拉菜單(select)的相關(guān)屬性值
- C#類中的屬性使用總結(jié)(詳解類的屬性)
- C#類中屬性與成員變量的使用小結(jié)
- C#中屬性和成員變量的區(qū)別說明
相關(guān)文章
C#創(chuàng)建數(shù)據(jù)庫及導(dǎo)入sql腳本的方法
這篇文章主要介紹了C#創(chuàng)建數(shù)據(jù)庫及導(dǎo)入sql腳本的方法,涉及C#針對數(shù)據(jù)庫的創(chuàng)建、連接、導(dǎo)入等相關(guān)操作技巧,需要的朋友可以參考下2015-12-12
Unity實現(xiàn)卡片循環(huán)滾動效果的示例詳解
這篇文章主要為大家詳細介紹了如何利用Unity實現(xiàn)卡片循環(huán)滾動的效果,文中的實現(xiàn)步驟講解詳細,具有一定的借鑒價值,需要的可以參考一下2022-12-12
C#實現(xiàn)子窗體與父窗體通信方法實例總結(jié)
這篇文章主要介紹了C#實現(xiàn)子窗體與父窗體通信方法,實例總結(jié)了常用的四種窗體通信方法,具有一定參考借鑒價值,需要的朋友可以參考下2015-09-09
C#結(jié)合JavaScript實現(xiàn)上傳視頻到騰訊云點播平臺的操作方法
這篇文章主要介紹了C#結(jié)合JavaScript實現(xiàn)上傳視頻到騰訊云點播平臺,上傳視頻功能,主要要解決兩個問題,一是在服務(wù)端通過C#生成簽名和SDKID,二是在客戶端通過JavaScript上傳視頻到騰訊云點播服務(wù)器,感興趣的朋友跟隨小編一起看看吧2023-11-11

