C#實現(xiàn)泛型類簡單分析
在向大家詳細介紹C#實現(xiàn)泛型類之前,首先讓大家了解下使用泛型集合,然后全面介紹C#實現(xiàn)泛型類。
使用泛型集合
有些人問我"面向?qū)ο缶幊蹋∣OP)的承諾在哪里?",我的回答是應(yīng)該從兩個方面來看OOP:你所使用的OOP和你創(chuàng)建的OOP。如果我們簡單地看一下如果沒有如例如Microsoft的.NET,Borland的VCL,以及所有的第三方組件這樣的OO框架,那么很多高級的應(yīng)用程序幾乎就無法創(chuàng)建。所以,我們可以說OOP已經(jīng)實現(xiàn)了它的承諾。不錯,生產(chǎn)好的OOP代碼是困難的并且可能是***挫敗性的;但是記住,你不必須一定要通過OOP來實現(xiàn)你的目標。因此,下面首先讓我們看一下泛型的使用。
當你用Visual Studio或C# Express等快速開發(fā)工具創(chuàng)建工程時,你會看到對于System.Collections.Generic命名空間的參考引用。在這個命名空間中,存在若干泛型數(shù)據(jù)結(jié)構(gòu)-它們都支持類型化的集合,散列,隊列,棧,字典以及鏈表等。為了使用這些強有力的數(shù)據(jù)結(jié)構(gòu),你所要做的僅是提供數(shù)據(jù)類型。
顯示出我們定義一個強類型集合的Customer對象是很容易的:
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace Generics{
- class Program{
- static void Main(string[] args){
- List<Customer> customers = new List<Customer>();
- customers.Add(new Customer("Motown-Jobs"));
- customers.Add(new Customer("Fatman's"));
- foreach (Customer c in customers)
- Console.WriteLine(c.CustomerName);
- Console.ReadLine();
- }
- }
- public class Customer{
- private string customerName = "";
- public string CustomerName{
- get { return customerName; }
- set { customerName = value; }
- }
- public Customer(string customerName){
- this.customerName = customerName;
- }
- }
- }
注意,我們有一個強類型集合-List<Customer>-對這個集合類本身來說不需要寫一句代碼。如果我們想要擴展列表customer,我們可以通過從List<Customer>繼承而派生一個新類。
C#實現(xiàn)泛型類
一種合理的實現(xiàn)某種新功能的方法是在原有的事物上進一步構(gòu)建。我們已經(jīng)了解強類型集合,并知道一種不錯的用來構(gòu)建泛型類的技術(shù)是使用一個特定類并刪除數(shù)據(jù)類型。也就是說,讓我們定義一個強類型集合CustomerList,并且來看一下它要把什么東西轉(zhuǎn)化成一個泛型類。
定義了一個類CustomerList:
- using System;
- using System.Collections;
- using System.Text;
- namespace Generics{
- public class CustomerList : CollectionBase{
- public CustomerList() { }
- public Customer this[int index]{
- get { return (Customer)List[index]; }
- set { List[index] = value; }
- }
- public int Add(Customer value)
- {return List.Add(value);}
- }
- }
【編輯推薦】