property是c#中的一個名詞。與其認爲是一個專有語法,還不如認爲是一系列語法的組合。property專屬的關鍵字就只有value。其他的性質實現都是用其他的方法的組合。property通過對一系列方法的靈活組合應用,能夠間接地對私有的成員變量進行賦值操作和得到值。因爲是間接地,私有變量的隱私性也是得到了保護。在下面這個例子中
定義一個Teacher類。老師的性別是隱私的,名頭也是隱私的。但是,可以定義一個property,用set和get方法間接地外部操作。注意這個專有的關鍵詞value,它代表在外部賦值時等號右邊的值,也就是輸入的值。在property的set內部,是可以對value進行操作的。set方法是非常靈活的,可以有多種操作。
namespace PropertyQuest
{
class Teacher {
string sex;//性別是私有的
string title;//頭銜是私有的.假如頭銜就是女老師,男老師
public string Title{
set{
sex = value.Split(' ')[0];//value是你在主程中,對Title賦值的時候,等號右邊傳遞的值.
//字符串的split()方法是以一個或若干個字符爲分隔符,分隔後的子串以字符串數組形式返回.這和Python蠻像的.
//[0]就是要得到第一個字符串.因爲我要輸入的Title是"female teacher"或者"male teacher",因此
//我以空格分割後,第一個字符串就是性別
title = value;//上一步操作sex,這一步操作title.說明set方法是很靈活的,一次可以設置多個成員變量
get {
return title;//間接得到title,title在set中已經設置
}
}
public string Sex {
get{
return sex;//間接得到sex的值.在上一個property中,sex被設置,在
//這個property中,單獨使用get,得到sex.很靈活的
}
}
}
class Program {
public static void Main(string[] args)
{
Teacher t = new Teacher();
t.Title = "female teacher";//等號右邊的就是value的值,賦給property Title後,在Title內部是會被操作的.
//間接地再賦給私有的成員變量.私有成員變量在當前類是不可見的,
//但是在Teacher類中是可見,因此可以被其他代碼塊使用,比如Title{}中的set{}.
Console.WriteLine(t.Sex);//通過property Sex間接得到私有成員變量sex的值
Console.WriteLine(t.Title);//通過property Title間接得到私有成員變量title的值
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
property還有一個用法,比較接近property這個單詞的本意。如果 有一項本來是對象的性質或者說屬性,但是要得到它還是要用一個函數。例如,知道一個矩形的長和寬,想知道它的面積。本來一個矩形的面積就是它的一個屬性,但是在傳統方法下,卻要用一個函數得到,感覺彆扭。
using System;
class Rectangle {
public float length;
public float width;
public float Area()
{
return length*width;
}
}
如果想得到一個Rectangle r的面積,明明是個屬性嘛,卻要用一個函數,r.Area().
但是用property方法,這個過程就自然地多。
class Rectangle {
public float length;
public float width;
public float Area{
get{
return length*width;
}
}
}
可以直接得到Rectangle r的面積屬性,用r.Area。Area 就是矩形的屬性嘛,那我就用對象名加屬性名,多麼自然。
完整程序如下:
using System;
class Rectangle {
public float length;
public float width;
public float Area{
get{
return length*width;
}
}
}
namespace ObjectInherit
{
class Program{
public static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.length = 100;
r.width = 50;
Console.WriteLine(r.Area);
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}