2013年8月21日

C#教材(5) 例外處理

  例外處理


  • 例外




 Ex: 除以分母
  int x = 0;
  int y = 123;
  Console.WriteLine("{0} 除以 {1} 等於 {2}" ,x, y, y/x);








  • 例外處理
(1)接收例外訊息


語法
try
{
    //錯誤的邏輯、流程或是變數偵錯的內容                      
}
catch (Exception ex)
{
    //拋出錯誤                      
}

語法
try
{
    //錯誤的邏輯、流程或是變數偵錯的內容                      
}
catch (Exception ex)
{
    //拋出錯誤                      
}finally
{
  //不管怎樣,都會做到此區塊
}



加上例外處理 :
int x = 0;
int y = 123;
try
{
Console.WriteLine("{0} 除以 {1} 等於 {2}", x, y, y / x);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());

}


  • 例外類別 :


Name Description
ApplicationException 使用者自訂例外類別,如果想要自訂類別可以繼承這個類別實作
SystemException 系統本身提供的例外類別,像DivideByZeroException或是ArithmeticException
IsoLatedStorageException 使用在IO系統中,隔離儲存作業失敗的例外情況
SUDSGeneratorException WSDL例外處理
InvalidActiveXStateException ActiveX控制項相關例外資訊


  • 拋出例外訊息方法:


(1) Message :
     回傳一個字串,其中表示例外訊息,利用這個屬性可以取得特定的狀況
     相關訊息說明。

(2) StackTrace :
    紀錄此例外的方法,拋出錯誤的堆疊。

(3) TargetSit:
      丟出例外的方法名稱。

(4) Source :
     取得錯誤丟出例外的應用程式或是物件名稱。

int x = 0;
int y = 123;
try
{
Console.WriteLine("{0} 除以 {1} 等於 {2}", x, y, y / x);
}
catch (Exception ex)
{
Console.WriteLine("例外訊息:{0}", ex.ToString());
Console.WriteLine("堆疊:{0}", ex.StackTrace);
Console.WriteLine("程式名稱:{0}", ex.Source);
Console.WriteLine("方法名稱:{0}", ex.StackTrace);
}

(2)自訂例外方法並拋出例外

當我們自訂例外類別時,我們需要自己撰寫邏輯去拋例外

語法
throw new 例外類別名稱()

  • 自訂例外類別

var Emp = new { name = "Jack" , salary=-1000f  };
try
{
if (Emp.salary < 0)
{
throw new MyException(); //拋出例外
}

Console.WriteLine("員工姓名:" +Emp.name);

}
catch (MyException myEx)
{
Console.WriteLine(myEx);

}

        //自訂錯誤類別
class MyException :ApplicationException
{
private String errorMessage ;

public MyException()
{
ZeroError();
}

public void ZeroError()
{
this.errorMessage = "薪水不為零" ;

}

public override string ToString()
{
return errorMessage ;

}

}
















C#教材(13) 字串與正規表示式

字串與正規表示式


 1. 字串基本屬性與函式
  • 字串(String)類別
    字串簡單來說就是由多個字元所組成的字元集合,字串類別為核心的命名空間
    System,當你建立一個string的變數既為引用他的類別。但是在字串的宣告我們
    通常不以new關鍵字去建立字串物件,主要原因是所有資料型態都可以轉成字串
    文字,所以通常C#允許用數值型別的方式去宣告字串。
  • 字串建構子
     I. public String(char[] charValue)
    II. public String(char[], int startIndex, int length);
   III. public String(char value, int conent)
 

  • 字串運算

   字串可以利用+運算子將字串做累加的動作,直接附加到原來的文字上面。

                   string name = " jack ," ;
                   string say = " hello" ;
                   string sentence = name + say;
                   Console .WriteLine(sentence);
                                   
                                    結果:  jack ,hello

  • 字串屬性的成員
      (1) 取得字串長度
           public int Length { get ;}     
     
      (2)刪除部分字串 
          Remove(int1,int2) :從int1(起始位置)開始刪除長度為int2的字串

     (3) 插入子字串: 
           Insert(int,string) :在int的位置插入string

    (4) 取出部分字串
           Substring(int) : 從參數開始取出剩下的字串
           Substring(int1,int2) : 取出int1開始長度為int2的字串
    (5) 索引
           IndexOf(string) : 傳回第一次搜尋到字串(string)的位置
           IndexOf(string,int) : 傳回第一次搜尋到字串(string)的位置,開始搜尋位置為int
           LastIndexOf(string) : 跟IndexOf功能類似,但從後面開始搜尋
           LastIndexOf(string,int) : 跟IndexOf功能類似,但從後面開始搜尋
           Replace(char,char) : 取代字元
    (6) 其他
          ToLower() 將英文轉成小寫
          ToUpper() 將英文轉成大寫
          Trim() 刪除字串前後的空白字元
          TrimEnd() 刪除字串尾部的空白字元
          TrimStart() 刪除字串開頭的空白字元
     (7) 字串運算
           int Compare(str1, str2 ) :  str1 == str2 回傳 0 ,  str1 > str2 回傳 1 , str1 < str2 回傳 -1
           int Compare(str1, str2, boolean )    宣告為true忽略大小寫

     (8) 擷取子字串
           string[] Split(param char[] charArray)


2.動態的字串與靜態字串比較
(1) String 類別
  string 是一個很強大的類別,它可以執行很多有用的方法,但是當我們重新給定
  string的值,需要重新規劃空間給他,效率很低。

 (2)StringBuilder類別
     Import: System.Text
    StringBuilder 物件會保留自己的字串緩衝區,所有新增、刪除、或是修改都只會
    在同一塊記憶體工作,優點是減少記憶體配置的動作除非緩衝區大小不夠處理
    時,才會作記憶體重新配置,預設容量為16,超過容量時會加倍到32,上限為   
    2,147,483,647
 
    相關函式:
     
    建構子:

Name Description
StringBuilder() 初始化,預設容量為16
StringBuilder(Int32) 初始化,預設容量可指定
StringBuilder(String) 初始化,預設字串內容
StringBuilder(Int32 start , Int32  max) 初始化,預設容量和上限
StringBuilder(String context, Int32 capacity) 初始化,預設容量和上限
StringBuilder(String, Int32, Int32, Int32) 初始化,指定位址、預設容量和上限

屬性 :

Name Description
Capacity 設定或是取得字串容量
Chars 設定或是取得字串容量.
Length 設定或是取得字串長度.
MaxCapacity 設定或是取得最大容量大小

方法:


Name Description
append 設定或是取得字串容量
appendFormat 設定或是取得字串容量.
AppendLine 設定或是取得字串長度.
Clear 設定或是取得最大容量大小
CopyTo   複製
Equals(object value) 是否相等
Insert() 插入一個字串
Remove 移除
Replace(string ,string) 取代另外一個字串

Ex:


規則運算式

1.基本概念:

(1). 跳脫字元(Character Escapes)
    某些字元代表的特殊意義,例如: * 、$等等
(2).分類字元(Character Classes)
    比對某種類型的字元,例如:[0-9]會將比對輸入的字串是否為數字、[dog]會將比對輸入
    的字串是否為d、o和g的字母。
(3).數量符號: (Quantifiers)
    用以指定所套用的樣式於字串,比對字串或是字元出現的次數。Ex: 5{2}找到55的字串
(4). 規則運算(Regular Expression Options)
    搜尋以及比對樣式
(5). 置換(Substitutions)
     取代功能


2. 實作程式
Import : using System.Text.RegularExpressions;

實作下列程式:

            string testString = @"今天天氣很好,我們一起去爬山,山上有很多猴子
                                        ,那些猴子很好玩";
            Console.WriteLine(testString);
            string matchStr = @"猴子";
            Regex regex = new Regex(matchStr);
            MatchCollection collection = regex.Matches(testString);
            Console.WriteLine("比對樣式:") ;
            foreach (Match match in collection)
            {
                Console.WriteLine("樣式: {0} , 位置:{1}",match,match.Index);
            }




          string testString = @"今天天氣很好,我們一起去爬山,山上有很多猴子,
                                     那些猴子很好玩";
            Console.WriteLine(testString);
            string matchStr = @"猴?";
            Regex regex = new Regex(matchStr);
            MatchCollection collection = regex.Matches(testString);
            Console.WriteLine("比對樣式:") ;
            foreach (Match match in collection)
            {
                Console.WriteLine("樣式: {0} , 位置:{1}",match,match.Index);
            }

    將matchStr 改為下列樣式:
      string matchStr = @"天{2}";
         

    將matchStr 改為下列樣式:[好天氣猴子]只要符合好、天、氣、猴、子的樣式。
      string matchStr = @"[好天氣猴子]";

字元


Name Description
? 設定或是取得字串容量
.    設定或是取得字串容量.
xy   設定或是取得字串長度.
+ 設定或是取得最大容量大小
  複製
^ 是否相等
$ 插入一個字串
\   移除
{n}  取代另外一個字串
{n,m} 比對前一個字元至少 n 次,至多 m 次,m、n 均為正整數
[xyz]    比對中括弧內的任一個字元
[^xyz] 比對不在中括弧內出現的任一個字元
\d  數字, 等於[0-9]
\D  非數字, 等於[^0-9]
\w  數字、字母、底線 [a-zA-Z0-9_]
\W 非數字、字母、底線 [^a-zA-Z0-9_]
\s  空白字元 [ \r\t\n\f]
\S 非空白字元 [^ \r\t\n\f]

  •  Regex方法

(1) public string[] Split(string strInput)
   

格式化

(1) public static string Format(string strformat, object obj)

Name Description
C或是 c 將數值轉換為貨幣數值格式。
D或是d 可以自動補零
E或是e 科學符號
F或是f 固定點
G或是g   一般
N或是n  編號 
P或是p 格式化以百分比的格式作輸出
X或是x  十六進制  
0 利用0將空白字串填滿
# 表示數字
.  小數點
 百分比
E0    科學符號
,   千位數分隔符號

Ex:
            double d2 = 10000;
            string result = "";
            result = string.Format("{0:###,###.000}",d2);
            Console.WriteLine(result);
            result = string.Format("{0:00}", 8);
            Console.WriteLine(result);
            result = string.Format("{0:P}", 0.5);
            Console.WriteLine(result);
            result = string.Format("{0:C}", 1000.00);
            Console.WriteLine(result);



(2)日期格式化:


Name Description
簡短日期模式
D  完整日期模式
t 簡短時間模式
T   完整時間模式
f  完整可排序日期/時間模式
F     完整可排序日期/時間模式
g   一般可排序日期/時間模式
G 一般可排序日期/時間模式
M/m  日月模式
R/r   RFC1123模式
s  ISO8601模式
通用日期/時間模式
通用日期/時間模式
Y/y    年月模式
d/dd   1~31數字來顯示日期,dd則是顯示完整名稱
ddd   顯示日期的縮寫
dddd  顯示完整名稱
顯示指定DateTime物件的紀元年代
h/hh  1-12小時,hh為在1-9之間前面補零                    
H/HH 0-23小時,HH為在1-9之間前面補零   
m/mm   顯示0-59分鐘,mm 為在1-9之間前面補零         
M/MM 顯示月份1-12月,MM為在1-9之間前面補零  
MMM 顯示月份縮寫
MMMM  顯示月份完整
s/ss   0-59,ss為在1-9之間前面補零
t/tt   AM或是PM
y/yy   顯示年份,yy為在1-9之間前面補零 
yyyy  顯示完整年份
z/zz  顯示目前得時區
zzz   顯示目前完整時區
日期分隔符號
''  顯示逸出字元
'   
%c 標準格式字元 
\c 顯示下一個字元為常值

EX:
      DateTime dt = DateTime.Now;
      Console.WriteLine("格式 yyyy/MM/dd HH:mm:ss: {0:yyyy/MM/dd HH:mm:ss}",
                                   dt); //(1) 完整表示日期
      Console.WriteLine("格式: yyyy/M/d H:m:s {0:yyyy/M/d H:m:s}", dt); //(2) 簡單表示日期
      Console.WriteLine("格式: {0:000,### yyyy } ",  dt); //(3) 日期格式與其他格式混和
      Console.WriteLine("格式: {0:yyyy年MM月dd日 } ", dt); //(4) 顯示中文年月份

(1) 通常疊字dd、MM等等會將所需要的日期時間如果是個位數自動補零
(2) 通常疊字dd、MM等等會將所需要的日期時間自動補零
(3) DateTime元件只會認識自己專屬的格式不會受到混淆
(4) 顯示中文年月份




  • ToString方法
toString除了可以將基本資料轉為字串外,他也可以自訂輸出的資料格式

Ex:

   int number = 1234;
Console.WriteLine(number.ToString("000,###")); //(1) 轉為數字格式
Console.WriteLine(123.55.ToString("000,###.0000")); //(2)直接轉為
Console.WriteLine(0.5.ToString("p"));  //(3) 直接轉為百分比
























2013年8月3日

C#教材(6) 函式與參照

函式與參照


  • 類別與基本型別
(1) 資料型別
在通常資料型別(char , int , bool , double..)或是稱數值型別(value type)都是編譯器實際儲存
空間給該變數,例如:當我宣告一個變數的資料型別為int時並指定值42給它,這時編譯器
會規畫32位元的記憶體空間來儲存它。

Ex:
int i = 31 ;         // 指派32位元給它
int temp =  i ;   // 宣告新的記憶體空間來存i的值
i = i+1 ;            // i =32      

由上面可以知道當我們利用基本型別做指派給別的變數、刪除或修改時,並不會影響
其他的變數,因為它是另外宣告一個空間來存放資料內容。

(2) 參照型別
當我們宣告一個類別Car名稱為c後,並將c指派給newC的變數,這時編譯器並不會跟資料
型別一樣存放實際的值,而是存放位址並指向同一個Car物件(資料實際放的位置)。當我
們改變newC的內容也會改變c的內容。我們可以利用一個成語來形容"牽一髮動全身"。

Ex:
class Car{
   public int speed ;
   public string name ;
 }

Car c = new Car()
Car newC = c    //將c實體位址指派給newC

  • null 和 nullable
在C#中不允許初始化宣告為null,但是真的必要宣告為null我們可以利用?來完成。在型別後面加上?號表示該變數為nullable數值型別。
Ex:
      int i = null  (X) 
      int? i = null (O)

當我們將i宣告為nullable時,我們可以利用HasValue來判斷是該值是否為null。

if ( ! i.HasValue )
   i = 99 ;
else
   System.Concole.WriteLine(i.Value);

Nullable屬性 :

HasValue : HasValue 屬於 bool 型別。當變數包含非 null 的值時,該屬性會設定為 true。
Value: 如果 HasValue 為 true,Value 會包含有意義的值。如果 HasValue 為 false,表示該變數為null,存取  Value 將會擲回InvalidOperationException
  • ref參數與out參數
(1) ref 參數
在參數型別前面,加上ref 可以讓參數變成參照型別,表示兩個變數是參考同一個物件。

Ex:
        public static void addOne(ref int param)
        {
            param++;
        }

        public static void Main()
        {
            int arg = 42;
            addOne( ref arg);
            System.Console.WriteLine(arg);
        }

常見的錯誤
        public static void addOne(ref int param)
        {
            param++;
        }

        public static void Main()
        {
            int arg = 42;
            addOne( arg);         //傳遞引數 1 時必須包含 'ref' 關鍵字
            System.Console.WriteLine(arg);
        }

(2) out 參數
   傳遞行為亦屬傳址, 但是不需要去做預先設定指派初始值給它,由函式傳值給它。
 

  • 以 ref 參數傳遞的引數必須先被初始化,out 則不需要。
  • out 參數要在離開目前的方法之前至少有一次指派值的動作。


static void Method(out int i)
{
i = 44;
}

static void Main(string[] args)
{
int value;
Method(out value);
Console.WriteLine("Value:" +value);

}

(3)







































2013年8月1日

C#教材(10) 陣列與集合

陣列與集合


之前有提過變數問題,但是當我們有一群相同資料型別,例如: 班上數學成績、
客戶名單等等。我們使用變數一個個儲存太過麻煩且沒有效率,這一類的資料
我們可以用陣列或是集合來做存取。
  • 陣列
  陣列是用來儲存資料群,我們可以將一個資料稱為元素,每個元素都有他們的
  位置方便我們存取,我們稱為索引值。   

(1) 一維陣列

陣列宣告方式:
                         DataType[] ArrayName = new DataType[] 

                         Ex: int[] men = new int[length] ;

初始化 :
     (i)預先給值
                         Ex:  int[] pins = new int[4] {9,3,7,2};

     (ii)個別元素
                         Ex:  int[] pins = new int[4] ;
                                 
 
讀取單一元素:
                        Ex:  pins[0]   //讀取第一個元素 ,結果為 : 9
                               pins[1]   //讀取第二個元素,結果為 : 3  
                               pins[2]   //讀取第三個元素 ,結果為 : 7
讀取全部元素:

     (i) FOR
int[] intArray = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

 for (int i = 0; i < intArray.Length; i++)
 {
     Console.Write(intArray[i] + ",");
  }

    (ii) FOREACH
    用來讀取陣列所有的元素,他會逐一檢視陣列的變數值,將他逐一將元素

int[] intArray = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

     foreach(int item in intArray)
{
Console.Write(item+",") ; 
}

(2) 多維陣列
                              DataType[,] ArrayName = new DataType[int d1, int d2] 
                              DataType[, ,] ArrayName = new DataType[int d1, int d2, int d3             
     (i)預先給值
                         Ex:   int[,] intMArray = new int[2, 4]{{1,2,3,4},{5,6,7,8}};

     (ii)個別元素
int[,] intMArray2 = new int[2, 4];
intMArray2[0, 2] = 10;
intMArray2[0, 3] = 20;
intMArray2[1, 3] = 100;

(3) 無固定長度陣列
                              DataType[][] ArrayName = new DataType[int d1][] 
                              DataType[] ArrayName = new DataType[int d2] 
                              DataType[] ArrayName = new DataType[int d3] 

    Ex:
  string[][] strArray = new string[4][];
strArray[0] = new string[3] { "apple", "banana", "pineapple" };
strArray[1] = new string[4] { "novel", "cartoon", "managize", "education" };

foreach (string[] onelayer in strArray)
{
                                //因為只有規劃兩列的陣列,所以當為null就不做取出
if (onelayer == null)
{
break;
}
foreach (string item in onelayer)
{
Console.Write(item+",");
}
Console.WriteLine();
}

  • System.Array類別
當我們建立陣列時,有些屬性或是方法他會自動的繼承,例如:GetValue取的元素值、
Copy複製物件等等。
    參考:http://msdn.microsoft.com/zh-tw/library/system.array.aspx
   
   宣告方式:
    int[] intArray = new int[10] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int[] copyArray = new int[10] ;

方法 說明 例子
void Copy(SourceArray, DestinactionArray, Int64)
void Copy(SourceArray, DestinactionArray, Int32)
複製陣列  Array.Copy(intArray, copyArray, 5);
//copyArray 內容為 1,2,3,4,5

void  Copy(Array, Int32, Array, Int32, Int32)
void  Copy(Array, Int32, Array, Int64, Int64)
說明 例子
int GetLength(Int64) 取得陣列的長度 intArray.GetLength(0)  //10
Object GetValue(Int64) 取得元素值 intArray.GetValue(1) // 2
Reverse(Array) 逆排序 Reverse// 10,9,8,7,6,5,4,3,2,1
Sort(Array) 順排序 Reverse // 1,2,3,4,5,6,7,8,9,10


建立隱含型別 :
   var names = new[] {"John" , "Diana" , "James"} ;
   var numbers = new[] {1 , 2 , 3.5 , 99.99} ;


  • 集合
集合可以說是物件的集合,他可以一次處理多個物件,.NET將物件規劃在System.Collection
你可以透過實作介面或是利用現成的方法去完成,集合的處理。接下來我們介紹集合幾個
重要的類別及介面:



  1. ArrayList

ArrayList是實作List介面的的類別,他跟Array很相似,陣列宣告時需要給定明確長度,但是
如果我們對一組資料可能沒有辦法決定明確的長度,這是建議可以使用ArrayList來宣告。

     //規劃員工類別: 職工編號、年紀、薪水
      class Employee :IComparable
{
public String no;
public int age;
public int salary;
}

        ArrayList alist = new ArrayList();
Console.WriteLine("初始化的長度: {0}",alist.Count) ;

//輸入員工清單
Console.WriteLine("===輸入員工清單===");
for (int i = 0; i <= 7; i++)
{
Random random = new Random() ;
Employee employee = new Employee() ;
employee.no = String.Format("{0}", i);
System.Threading.Thread.Sleep(500);
employee.age = random.Next(18, 65);
employee.salary = random.Next(15000, 50000);
alist.Add(employee);
}

//插入空降部隊
alist.Insert(3, new Employee { no="8" , salary=50000, age=30 });

//列出員工清單
foreach (Employee emp in alist)
{
Console.Write("編號:{0},",emp.no) ;
Console.Write("年齡:{0},", emp.age);
Console.Write("薪水:{0},", emp.salary);
Console.WriteLine() ;
}

Console.WriteLine("===移除空降部隊===");
alist.Remove(alist[3]);  //移除空降部隊

Console.WriteLine("===組織改選===");
alist.Reverse();   //組織改選

//列出員工清單
foreach (Employee emp in alist)
{
Console.Write("編號:{0},", emp.no);
Console.Write("年齡:{0},", emp.age);
Console.Write("薪水:{0},", emp.salary);
Console.WriteLine();
}

結果:



2. IComparable介面
   這個介面主要可以用來實現排序的功能,依據某個值是否大於、 等於或小於另傳
   回 1、 0 或-1

    //實作年齡 IComparable介面
  class Employee :IComparable
{
public String no;
public int age;
public int salary;

public int CompareTo(object obj)
{
Employee refEmp = (Employee)obj;
return this.age.CompareTo(refEmp.age);
}
}

ArrayList alist = new ArrayList();
Console.WriteLine("初始化的長度: {0}",alist.Count) ;

//輸入員工清單
Console.WriteLine("===輸入員工清單===");
for (int i = 0; i <= 7; i++)
{
Random random = new Random() ;
Employee employee = new Employee() ;
System.Threading.Thread.Sleep(500);
employee.no = random.Next(1, 20).ToString();
employee.age = random.Next(18, 65);
employee.salary = random.Next(15000, 50000);
alist.Add(employee);
}

//插入空降部隊
alist.Insert(3, new Employee { no="8" , salary=50000, age=30 });

//員工以年齡排序
alist.Sort();
//列出員工清單
foreach (Employee emp in alist)
{
Console.Write("編號:{0},",emp.no) ;
Console.Write("年齡:{0},", emp.age);
Console.Write("薪水:{0},", emp.salary);
Console.WriteLine() ;
}

3. 列舉
逐一列舉出元素,集合常用的模式,而IEnumberator負責這些方法的定義,如MoveNext、
Reset、MoveNext等等。

        class EnumEx1:IEnumerable
{
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
}

實例:
      public class Employee : IComparable, IEnumerable, IEnumerator
{
public String no;
public int age;
public int salary;

int currentIndex = -1;
ArrayList empList = new ArrayList();

public Employee()
{

}

public Employee(ArrayList empolyeeArrayList)
{
this.empList = empolyeeArrayList;
}

public int CompareTo(object obj)
{
Employee refEmp = (Employee)obj;
return this.age.CompareTo(refEmp.age);
}

//IEnumerable
public IEnumerator GetEnumerator()
{
return this.empList.GetEnumerator();
}

//IEnumerator
public object Current
{
get { return empList[currentIndex]; }
}

public bool MoveNext()
{
bool result = false;
if (empList.Count >= currentIndex)
{
currentIndex += -1;
result = true;
}

return result;
}

public void Reset()
{
currentIndex = -1;
}
}

  class ArrayListEx
{
public static void Main()
{
ArrayList alist = new ArrayList();
Console.WriteLine("初始化的長度: {0}",alist.Count) ;

//輸入員工清單
Console.WriteLine("===輸入員工清單===");
for (int i = 0; i <= 7; i++)
{
Random random = new Random() ;
Employee employee = new Employee() ;
System.Threading.Thread.Sleep(500);
employee.no = random.Next(1, 20).ToString();
employee.age = random.Next(18, 65);
employee.salary = random.Next(15000, 50000);
alist.Add(employee);
}

Employee empAction = new Employee(alist);
IEnumerator enumtor = empAction.GetEnumerator();

while(enumtor.MoveNext())
{
Employee employee = (Employee)enumtor.Current;
Console.WriteLine("no:"+employee.no + "\t");
Console.WriteLine("age:"+employee.age + "\t");
Console.WriteLine("salary:"+employee.salary + "\t");
}
}




常用的介面

  1. ICollection介面
當我們實作ICollection介面時,我們需要實作下列的方法。


class CollectionEx1 : ICollection
{
public void CopyTo(Array array, int index)
{
throw new NotImplementedException();
}

public int Count
{
get { throw new NotImplementedException(); }
}

public bool IsSynchronized
{
get { throw new NotImplementedException(); }
}

public object SyncRoot
{
get { throw new NotImplementedException(); }
}

public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
}

      2.IList

      class IListExt :IList
{
public int Add(object value)
{
throw new NotImplementedException();
}

public void Clear()
{
throw new NotImplementedException();
}

public bool Contains(object value)
{
throw new NotImplementedException();
}

public int IndexOf(object value)
{
throw new NotImplementedException();
}

public void Insert(int index, object value)
{
throw new NotImplementedException();
}

public bool IsFixedSize
{
get { throw new NotImplementedException(); }
}

public bool IsReadOnly
{
get { throw new NotImplementedException(); }
}

public void Remove(object value)
{
throw new NotImplementedException();
}

public void RemoveAt(int index)
{
throw new NotImplementedException();
}

public object this[int index]
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}

public void CopyTo(Array array, int index)
{
throw new NotImplementedException();
}

public int Count
{
get { throw new NotImplementedException(); }
}

public bool IsSynchronized
{
get { throw new NotImplementedException(); }
}

public object SyncRoot
{
get { throw new NotImplementedException(); }
}

public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
}






  • 堆疊與促列(stack & queue)

(1) 堆疊(stack)
    堆疊是一種後進先出的資料結構,就是跟發牌的排列一樣,我們可以利用stack的類別
    去使用,他分別實作ICollection、IEnumerable和ICloneable這三種介面。stack提供兩個重
    要的方法Pop和Push,Pop為放入以及Push為取出。
   
    Ex:
           Stack numberStack = new Stack();
            numberStack.Push("dog");
            numberStack.Push("a");
            numberStack.Push("is");
            numberStack.Push("it");
            Console.WriteLine("Count:{0} ", numberStack.Count);

            Console.WriteLine("{0} ", numberStack.Pop());
            Console.WriteLine("{0} ", numberStack.Pop());
            Console.WriteLine("{0} ", numberStack.Pop());
            Console.WriteLine("{0} ", numberStack.Pop());
   
     Ans : it is a dog


 (2)促列(queue)
 促列是一種先進先出的資料結構,最先加入會先被取出,例如: 排隊、網路資料處理等等
 Queue分別實作ICollection、IEnumerable和ICloneable這三種介面。queue的預設容量大小32。
 queue提供兩個重要的方法enqueue和dequeue,enqueue為放入以及dequeue為取出。

        public static void Main()
        {
            Queue queue = new Queue();
            queue.Enqueue("it");
            queue.Enqueue("is");
            queue.Enqueue("a");
            queue.Enqueue("dog");

            Console.WriteLine("{0}",queue.Dequeue());
            Console.WriteLine("{0}", queue.Dequeue());
            Console.WriteLine("{0}", queue.Dequeue());
            Console.WriteLine("{0}", queue.Dequeue());
        }

 Ans : it is a dog



(3)雜湊(hashtable)
 它是一種資料結構的方式,透過數學方函式運算,將集合中的元素經由雜湊函式轉換
 來對應表格中的索引值。