詳解C#中的屬性和屬性的使用
屬性
屬性是一種成員,它提供靈活的機(jī)制來讀取、寫入或計(jì)算私有字段的值。屬性可用作公共數(shù)據(jù)成員,但它們實(shí)際上是稱為“訪問器”的特殊方法。這使得可以輕松訪問數(shù)據(jù),還有助于提高方法的安全性和靈活性。
在此示例中,TimePeriod 類存儲(chǔ)時(shí)間段。該類在內(nèi)部以秒為單位存儲(chǔ)時(shí)間,但是名為 Hours 的屬性允許客戶端以小時(shí)為單位指定時(shí)間。 Hours 屬性的訪問器執(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é)果的屬性很常見。下面的語法快捷方式使用 => 來定義這些屬性:
public string Name => First + " " + Last;
屬性必須為只讀,并且你不能使用 get 訪問器關(guān)鍵字。
使用屬性
屬性結(jié)合了字段和方法的多個(gè)方面。對于對象的用戶,屬性顯示為字段,訪問該屬性需要相同的語法。對于類的實(shí)現(xiàn)者,屬性是一個(gè)或兩個(gè)代碼塊,表示一個(gè) get 訪問器和/或一個(gè) set 訪問器。當(dāng)讀取屬性時(shí),執(zhí)行 get 訪問器的代碼塊;當(dāng)向?qū)傩苑峙湟粋€(gè)新值時(shí),執(zhí)行 set 訪問器的代碼塊。不具有 set 訪問器的屬性被視為只讀屬性。不具有 get 訪問器的屬性被視為只寫屬性。同時(shí)具有這兩個(gè)訪問器的屬性是讀寫屬性。
屬性具有多種用法:它們可在允許更改前驗(yàn)證數(shù)據(jù);它們可透明地公開某個(gè)類上的數(shù)據(jù),該類的數(shù)據(jù)實(shí)際上是從其他源(例如數(shù)據(jù)庫)檢索到的;當(dāng)數(shù)據(jù)被更改時(shí),它們可采取行動(dòng),例如引發(fā)事件或更改其他字段的值。
屬性在類塊中是按以下方式來聲明的:指定字段的訪問級別,接下來指定屬性的類型和名稱,然后跟上聲明 get 訪問器和/或 set 訪問器的代碼塊。例如:
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 訪問器可確保 Month 值設(shè)置為 1 和 12 之間。 Month 屬性使用私有字段來跟蹤該實(shí)際值。屬性的數(shù)據(jù)的真實(shí)位置經(jīng)常稱為屬性的“后備存儲(chǔ)”。屬性使用作為后備存儲(chǔ)的私有字段是很常見的。將字段標(biāo)記為私有可確保該字段只能通過調(diào)用屬性來更改。
。
get 訪問器
get 訪問器體與方法體相似。它必須返回屬性類型的值。執(zhí)行 get 訪問器相當(dāng)于讀取字段的值。例如,當(dāng)正在從 get 訪問器返回私有變量并且啟用了優(yōu)化時(shí),對 get 訪問器方法的調(diào)用由編譯器進(jìn)行內(nèi)聯(lián),因此不存在方法調(diào)用的系統(tǒng)開銷。然而,由于在編譯時(shí)編譯器不知道在運(yùn)行時(shí)實(shí)際調(diào)用哪個(gè)方法,因此無法內(nèi)聯(lián)虛擬 get 訪問器。以下是返回私有字段 name 的值的 get 訪問器:
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 訪問器以讀取該屬性的值。例如:
Person person = new Person(); //... System.Console.Write(person.Name); // the get accessor is invoked here
get 訪問器必須以 return 或 throw 語句終止,并且控制權(quán)不能離開訪問器體。
通過使用 get 訪問器更改對象的狀態(tài)不是一種好的編程風(fēng)格。例如,以下訪問器在每次訪問 number 字段時(shí)都會(huì)產(chǎn)生更改對象狀態(tài)的副作用。
private int number;
public int Number
{
get
{
return number++; // Don't do this
}
}
get 訪問器可用于返回字段值,或用于計(jì)算并返回字段值。例如:
class Employee
{
private string name;
public string Name
{
get
{
return name != null ? name : "NA";
}
}
}
在上一個(gè)代碼段中,如果不對 Name 屬性賦值,它將返回值 NA。
set 訪問器
set 訪問器類似于返回類型為 void 的方法。它使用稱為 value 的隱式參數(shù),此參數(shù)的類型是屬性的類型。在下面的示例中,將 set 訪問器添加到 Name 屬性:
class Person
{
private string name; // the name field
public string Name // the Name property
{
get
{
return name;
}
set
{
name = value;
}
}
}
當(dāng)對屬性賦值時(shí),用提供新值的參數(shù)調(diào)用 set 訪問器。例如:
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 訪問器中,對局部變量聲明使用隱式參數(shù)名稱 value 是錯(cuò)誤的。
此例說明了實(shí)例、靜態(tài)和只讀屬性。它從鍵盤接受雇員的姓名,按 1 遞增 NumberOfEmployees,并顯示雇員的姓名和編號。
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
此示例說明如何訪問基類中由派生類中具有同一名稱的另一個(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) 用于訪問基類中的隱藏屬性:
((Employee)m1).Name = "Mary";
在此例中,Cube 和 Square 這兩個(gè)類實(shí)現(xiàn)抽象類 Shape,并重寫它的抽象 Area 屬性。注意屬性上 override 修飾符的使用。程序接受輸入的邊長并計(jì)算正方形和立方體的面積。它還接受輸入的面積并計(jì)算正方形和立方體的相應(yī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
- 輕松學(xué)習(xí)C#的屬性
- C#實(shí)現(xiàn)獲取不同對象中名稱相同屬性的方法
- C#實(shí)現(xiàn)ComboBox控件顯示出多個(gè)數(shù)據(jù)源屬性的方法
- C#中使用反射遍歷一個(gè)對象屬性及值的小技巧
- C#索引屬性用法實(shí)例分析
- C#實(shí)現(xiàn)ProperTyGrid自定義屬性的方法
- C#屬性(Attribute)用法實(shí)例解析
- C#利用反射來判斷對象是否包含某個(gè)屬性的實(shí)現(xiàn)方法
- C#類中的屬性使用總結(jié)(詳解類的屬性)
- C#類中屬性與成員變量的使用小結(jié)
- C#中屬性和成員變量的區(qū)別說明
相關(guān)文章
C#?Socket數(shù)據(jù)接收的三種實(shí)現(xiàn)方式
本文主要介紹了C#?Socket數(shù)據(jù)接收的三種實(shí)現(xiàn)方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
C# Record構(gòu)造函數(shù)的行為更改詳解
C# 9 中的record類型是僅具有只讀屬性的輕量級、不可變數(shù)據(jù)類型(或輕量級類),下面這篇文章主要給大家介紹了關(guān)于C# Record構(gòu)造函數(shù)的行為更改的相關(guān)資料,需要的朋友可以參考下2021-08-08
C#簡易人機(jī)對抗“石頭剪刀布”游戲的實(shí)現(xiàn)
本文主要介紹了C#簡易人機(jī)對抗“石頭剪刀布”游戲的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-05-05
C# Ado.net實(shí)現(xiàn)讀取SQLServer數(shù)據(jù)庫存儲(chǔ)過程列表及參數(shù)信息示例
這篇文章主要介紹了C# Ado.net實(shí)現(xiàn)讀取SQLServer數(shù)據(jù)庫存儲(chǔ)過程列表及參數(shù)信息,結(jié)合實(shí)例形式總結(jié)分析了C#針對SQLServer數(shù)據(jù)庫存儲(chǔ)過程及參數(shù)信息的各種常見操作技巧,需要的朋友可以參考下2019-02-02

