一、屬性
在屬性的訪(fǎng)問(wèn)聲明中:
◆只有set訪(fǎng)問(wèn)器,表明屬性的值只能進(jìn)行設置而不能讀出。
◆只有g(shù)et訪(fǎng)問(wèn)器,表明屬性的值是只讀的,不能改寫(xiě)。
◆同時(shí)具有set訪(fǎng)問(wèn)器和get訪(fǎng)問(wèn)器,表明屬性的值的讀寫(xiě)都是允許的。
除了使用了abstract修飾符的抽象屬性,每個(gè)訪(fǎng)問(wèn)器的執行體中只有分號“;”,其它所有屬性的get訪(fǎng)問(wèn)器都通過(guò)return來(lái)讀取屬性的值,set訪(fǎng)問(wèn)器都通過(guò)value來(lái)設置屬性的值。
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
...{
class Man
...{
private int _x;
public Man(int xx)
...{
this._x = xx;
}
public int x
...{
get
...{
Console.WriteLine("get x: {0}", _x);
return _x;
}
set
...{
Console.WriteLine("set x:{0} a new value {1}", _x, value);
_x = value;
}
}
public static Man operator ++(Man man)
...{
man.x = man.x + 100 ;//先運行一次 x.get,再運行一次 x.set
return man;
}
}
class Program
...{
static void Main(string[] args)
...{
Man man = new Man(33);
Console.WriteLine("befor add:x-{0}", man.x);//運行一次 x.get
man++;
Console.WriteLine("befor add:x-{0}", man.x);//運行一次 x.get
return;
}
}
}
運行結果:
get x: 33
befor add:x-33
get x: 33
set x:33 a new value 133
get x: 133
befor add:x-133
每次 運行 man.x ,set 或者 get 都會(huì )自動(dòng)運行,對屬性進(jìn)行讀或者寫(xiě)。
感覺(jué)優(yōu)點(diǎn)怪怪的,不過(guò)確實(shí)蠻方便的。
二、異常處理
異常處理貌似和java一樣。
執行代碼拋出異常,catch捕獲異常,finally執行收尾工作(finally不管是否捕獲異常都會(huì )執行)。
叁、裝箱與拆箱
@裝箱是將值類(lèi)型轉換為引用類(lèi)型
@拆箱是將引用類(lèi)型轉換為值類(lèi)型
@利用裝箱和拆箱功能,可通過(guò)允許值類(lèi)型的任何值與 Object 類(lèi)型的值相互轉換,將值類(lèi)型與引用類(lèi)型鏈接起來(lái)
裝箱 值類(lèi)型的數據轉換為object類(lèi)
隱式轉換
拆箱 將封裝的對象轉換為值
顯式轉換
is運算符 <operand> is <type>
<operand> 可轉換為<type> true
as運算符 <operand> as <type>
int val = 100;
object obj = val; //裝箱:值類(lèi)型到引用類(lèi)型
int num = (int) obj; //拆箱:引用類(lèi)型到值類(lèi)型
//被裝過(guò)箱的對象才能被拆箱??? 四、C#通過(guò)提供索引器,可以象處理數組一樣處理對象。特別是屬性,每一個(gè)元素都以一個(gè)get或set方法暴露。
寫(xiě)了個(gè)實(shí)驗的,好像長(cháng)了點(diǎn),暈。。。。個(gè)先。。。

class MyName //姓名對象
...{
private string _first_name; //姓
private string _second_name;//名
public MyName(String first_name, String second_name)
...{//構造函數
this._first_name = first_name;
this._second_name = second_name;
}
public String FirstName
...{//屬性
get ...{ return _first_name; }
set ...{ this._first_name = value; }
}
public String SecondName
...{/**/////屬性
get ...{ return _second_name; }
set ...{ this._second_name = value; }
}
}
class MynameList //測試索引器
...{
private MyName[] names;
public MynameList(int capacity)
...{
this.names = new MyName[capacity];
}
public MyName this[String first_name]//用姓索引
...{
get
...{
// 遍歷數組中是否存在該姓的對象,若存在返回第一個(gè)找到的對象
foreach (MyName curName in names)
...{
if (curName.FirstName == first_name)
return curName;
}
Console.WriteLine("未找到");
return null; // 使用 null 指示失敗
}
}
public MyName this[int index] //用下標索引
...{
get
...{
// 驗證索引范圍
if (index < 0 || index >= names.Length)
...{
Console.WriteLine("索引無(wú)效");
return null;// 使用 null 指示失敗
}
return names[index]; // 對于有效索引,返回請求的對象
}
set
...{
if (index < 0 || index >= names.Length)
...{
Console.WriteLine("索引無(wú)效");
return;
}
names[index] = value;
}
}
}
五、委托