屬性
屬性是一種成員,它提供靈活的機(jī)制來(lái)讀取、寫入或計(jì)算私有字段的值。屬性可用作公共數(shù)據(jù)成員,但它們實(shí)際上是稱為“訪問(wèn)器”的特殊方法。這使得可以輕松訪問(wèn)數(shù)據(jù),還有助于提高方法的安全性和靈活性。
在此示例中,TimePeriod 類存儲(chǔ)時(shí)間段。該類在內(nèi)部以秒為單位存儲(chǔ)時(shí)間,但是名為 Hours 的屬性允許客戶端以小時(shí)為單位指定時(shí)間。 Hours 屬性的訪問(wèn)器執(zhí)行小時(shí)與秒之間的轉(zhuǎn)換。
class TimePeriod{ private double seconds; public double Hours { get { return seconds / 3600; } set { seconds = value * 3600; } }}class Program{ static void Main() { TimePeriod t = new TimePeriod(); // Assigning the Hours property causes the 'set' accessor to be called. t.Hours = 24; // Evaluating the Hours property causes the 'get' accessor to be called. System.Console.WriteLine("Time in hours: " + t.Hours); }}輸出:
Time in hours: 24
表達(dá)式主體定義
直接只返回表達(dá)式結(jié)果的屬性很常見。下面的語(yǔ)法快捷方式使用 => 來(lái)定義這些屬性:
public string Name => First + " " + Last;
屬性必須為只讀,并且你不能使用 get 訪問(wèn)器關(guān)鍵字。
使用屬性
屬性結(jié)合了字段和方法的多個(gè)方面。對(duì)于對(duì)象的用戶,屬性顯示為字段,訪問(wèn)該屬性需要相同的語(yǔ)法。對(duì)于類的實(shí)現(xiàn)者,屬性是一個(gè)或兩個(gè)代碼塊,表示一個(gè) get 訪問(wèn)器和/或一個(gè) set 訪問(wèn)器。當(dāng)讀取屬性時(shí),執(zhí)行 get 訪問(wèn)器的代碼塊;當(dāng)向?qū)傩苑峙湟粋€(gè)新值時(shí),執(zhí)行 set 訪問(wèn)器的代碼塊。不具有 set 訪問(wèn)器的屬性被視為只讀屬性。不具有 get 訪問(wèn)器的屬性被視為只寫屬性。同時(shí)具有這兩個(gè)訪問(wèn)器的屬性是讀寫屬性。
屬性具有多種用法:它們可在允許更改前驗(yàn)證數(shù)據(jù);它們可透明地公開某個(gè)類上的數(shù)據(jù),該類的數(shù)據(jù)實(shí)際上是從其他源(例如數(shù)據(jù)庫(kù))檢索到的;當(dāng)數(shù)據(jù)被更改時(shí),它們可采取行動(dòng),例如引發(fā)事件或更改其他字段的值。
屬性在類塊中是按以下方式來(lái)聲明的:指定字段的訪問(wèn)級(jí)別,接下來(lái)指定屬性的類型和名稱,然后跟上聲明 get 訪問(wèn)器和/或 set 訪問(wèn)器的代碼塊。例如:
public class Date{ private int month = 7; // Backing store public int Month { get { return month; } set { if ((value > 0) && (value < 13)) { month = value; } } }}在此示例中,Month 是作為屬性聲明的,這樣 set 訪問(wèn)器可確保 Month 值設(shè)置為 1 和 12 之間。 Month 屬性使用私有字段來(lái)跟蹤該實(shí)際值。屬性的數(shù)據(jù)的真實(shí)位置經(jīng)常稱為屬性的“后備存儲(chǔ)”。屬性使用作為后備存儲(chǔ)的私有字段是很常見的。將字段標(biāo)記為私有可確保該字段只能通過(guò)調(diào)用屬性來(lái)更改。
。
get 訪問(wèn)器
get 訪問(wèn)器體與方法體相似。它必須返回屬性類型的值。執(zhí)行 get 訪問(wèn)器相當(dāng)于讀取字段的值。例如,當(dāng)正在從 get 訪問(wèn)器返回私有變量并且啟用了優(yōu)化時(shí),對(duì) get 訪問(wèn)器方法的調(diào)用由編譯器進(jìn)行內(nèi)聯(lián),因此不存在方法調(diào)用的系統(tǒng)開銷。然而,由于在編譯時(shí)編譯器不知道在運(yùn)行時(shí)實(shí)際調(diào)用哪個(gè)方法,因此無(wú)法內(nèi)聯(lián)虛擬 get 訪問(wèn)器。以下是返回私有字段 name 的值的 get 訪問(wèn)器:
class Person{ private string name; // the name field public string Name // the Name property { get { return name; } }}當(dāng)引用屬性時(shí),除非該屬性為賦值目標(biāo),否則將調(diào)用 get 訪問(wèn)器以讀取該屬性的值。例如:
Person person = new Person();//...System.Console.Write(person.Name); // the get accessor is invoked here
get 訪問(wèn)器必須以 return 或 throw 語(yǔ)句終止,并且控制權(quán)不能離開訪問(wèn)器體。
通過(guò)使用 get 訪問(wèn)器更改對(duì)象的狀態(tài)不是一種好的編程風(fēng)格。例如,以下訪問(wèn)器在每次訪問(wèn) number 字段時(shí)都會(huì)產(chǎn)生更改對(duì)象狀態(tài)的副作用。
private int number;public int Number{ get { return number++; // Don't do this }}get 訪問(wèn)器可用于返回字段值,或用于計(jì)算并返回字段值。例如:
class Employee{ private string name; public string Name { get { return name != null ? name : "NA"; } }}在上一個(gè)代碼段中,如果不對(duì) Name 屬性賦值,它將返回值 NA。
set 訪問(wèn)器
set 訪問(wèn)器類似于返回類型為 void 的方法。它使用稱為 value 的隱式參數(shù),此參數(shù)的類型是屬性的類型。在下面的示例中,將 set 訪問(wèn)器添加到 Name 屬性:
class Person{ private string name; // the name field public string Name // the Name property { get { return name; } set { name = value; } }}當(dāng)對(duì)屬性賦值時(shí),用提供新值的參數(shù)調(diào)用 set 訪問(wèn)器。例如:
Person person = new Person();person.Name = "Joe"; // the set accessor is invoked here System.Console.Write(person.Name); // the get accessor is invoked here
在 set 訪問(wèn)器中,對(duì)局部變量聲明使用隱式參數(shù)名稱 value 是錯(cuò)誤的。
此例說(shuō)明了實(shí)例、靜態(tài)和只讀屬性。它從鍵盤接受雇員的姓名,按 1 遞增 NumberOfEmployees,并顯示雇員的姓名和編號(hào)。
public class Employee{ public static int NumberOfEmployees; private static int counter; private string name; // A read-write instance property: public string Name { get { return name; } set { name = value; } } // A read-only static property: public static int Counter { get { return counter; } } // A Constructor: public Employee() { // Calculate the employee's number: counter = ++counter + NumberOfEmployees; }}class TestEmployee{ static void Main() { Employee.NumberOfEmployees = 107; Employee e1 = new Employee(); e1.Name = "Claude Vige"; System.Console.WriteLine("Employee number: {0}", Employee.Counter); System.Console.WriteLine("Employee name: {0}", e1.Name); }}輸出:
Employee number: 108 Employee name: Claude Vige
此示例說(shuō)明如何訪問(wèn)基類中由派生類中具有同一名稱的另一個(gè)屬性所隱藏的屬性。
public class Employee{ private string name; public string Name { get { return name; } set { name = value; } }}public class Manager : Employee{ private string name; // Notice the use of the new modifier: public new string Name { get { return name; } set { name = value + ", Manager"; } }}class TestHiding{ static void Main() { Manager m1 = new Manager(); // Derived class property. m1.Name = "John"; // Base class property. ((Employee)m1).Name = "Mary"; System.Console.WriteLine("Name in the derived class is: {0}", m1.Name); System.Console.WriteLine("Name in the base class is: {0}", ((Employee)m1).Name); }}輸出:
Name in the derived class is: John, Manager Name in the base class is: Mary
以下是上一個(gè)示例中的要點(diǎn):
派生類中的屬性 Name 隱藏基類中的屬性 Name。在這種情況下,派生類的屬性聲明中使用 new 修飾符:
public new string Name
轉(zhuǎn)換 (Employee) 用于訪問(wèn)基類中的隱藏屬性:
((Employee)m1).Name = "Mary";
在此例中,Cube 和 Square 這兩個(gè)類實(shí)現(xiàn)抽象類 Shape,并重寫它的抽象 Area 屬性。注意屬性上 override 修飾符的使用。程序接受輸入的邊長(zhǎng)并計(jì)算正方形和立方體的面積。它還接受輸入的面積并計(jì)算正方形和立方體的相應(yīng)邊長(zhǎng)。
abstract class Shape{ public abstract double Area { get; set; }}class Square : Shape{ public double side; public Square(double s) //constructor { side = s; } public override double Area { get { return side * side; } set { side = System.Math.Sqrt(value); } }}class Cube : Shape{ public double side; public Cube(double s) { side = s; } public override double Area { get { return 6 * side * side; } set { side = System.Math.Sqrt(value / 6); } }}class TestShapes{ static void Main() { // Input the side: System.Console.Write("Enter the side: "); double side = double.Parse(System.Console.ReadLine()); // Compute the areas: Square s = new Square(side); Cube c = new Cube(side); // Display the results: System.Console.WriteLine("Area of the square = {0:F2}", s.Area); System.Console.WriteLine("Area of the cube = {0:F2}", c.Area); System.Console.WriteLine(); // Input the area: System.Console.Write("Enter the area: "); double area = double.Parse(System.Console.ReadLine()); // Compute the sides: s.Area = area; c.Area = area; // Display the results: System.Console.WriteLine("Side of the square = {0:F2}", s.side); System.Console.WriteLine("Side of the cube = {0:F2}", c.side); }}輸出:
Enter the side: 4 Area of the square = 16.00 Area of the cube = 96.00 Enter the area: 24 Side of the square = 4.90 Side of the cube = 2.00
新聞熱點(diǎn)
疑難解答
圖片精選