深入解析C#中的泛型類與泛型接口
泛型類
泛型類封裝不是特定于具體數(shù)據(jù)類型的操作。泛型類最常用于集合,如鏈接列表、哈希表、堆棧、隊列、樹等。像從集合中添加和移除項這樣的操作都以大體上相同的方式執(zhí)行,與所存儲數(shù)據(jù)的類型無關(guān)。
對于大多數(shù)需要集合類的方案,推薦的方法是使用 .NET Framework 類庫中所提供的類。
- 一般情況下,創(chuàng)建泛型類的過程為:從一個現(xiàn)有的具體類開始,逐一將每個類型更改為類型參數(shù),直至達(dá)到通用化和可用性的最佳平衡。創(chuàng)建您自己的泛型類時,需要特別注意以下事項:
- 將哪些類型通用化為類型參數(shù)。
- 通常,能夠參數(shù)化的類型越多,代碼就會變得越靈活,重用性就越好。但是,太多的通用化會使其他開發(fā)人員難以閱讀或理解代碼。
- 如果存在約束,應(yīng)對類型參數(shù)應(yīng)用什么約束。
- 一條有用的規(guī)則是,應(yīng)用盡可能最多的約束,但仍使您能夠處理必須處理的類型。例如,如果您知道您的泛型類僅用于引用類型,則應(yīng)用類約束。這可以防止您的類被意外地用于值類型,并允許您對 T 使用 as 運算符以及檢查空值。
- 是否將泛型行為分解為基類和子類。
- 由于泛型類可以作為基類使用,此處適用的設(shè)計注意事項與非泛型類相同。請參見本主題后面有關(guān)從泛型基類繼承的規(guī)則。
- 是否實現(xiàn)一個或多個泛型接口。
例如,如果您設(shè)計一個類,該類將用于創(chuàng)建基于泛型的集合中的項,則可能必須實現(xiàn)一個接口,如 IComparable<T>,其中 T 是您的類的類型。
類型參數(shù)和約束的規(guī)則對于泛型類行為有幾方面的含義,特別是關(guān)于繼承和成員可訪問性。您應(yīng)當(dāng)先理解一些術(shù)語,然后再繼續(xù)進(jìn)行。對于泛型類 Node<T>,客戶端代碼可通過指定類型參數(shù)來引用該類,以便創(chuàng)建封閉式構(gòu)造類型 (Node<int>)?;蛘呖梢宰岊愋蛥?shù)處于未指定狀態(tài)(例如在指定泛型基類時)以創(chuàng)建開放式構(gòu)造類型 (Node<T>)。泛型類可以從具體的、封閉式構(gòu)造或開放式構(gòu)造基類繼承:
class BaseNode { }
class BaseNodeGeneric<T> { }
// concrete type
class NodeConcrete<T> : BaseNode { }
//closed constructed type
class NodeClosed<T> : BaseNodeGeneric<int> { }
//open constructed type
class NodeOpen<T> : BaseNodeGeneric<T> { }
非泛型類(換句話說,即具體類)可以從封閉式構(gòu)造基類繼承,但無法從開放式構(gòu)造類或類型參數(shù)繼承,因為在運行時客戶端代碼無法提供實例化基類所需的類型參數(shù)。
//No error
class Node1 : BaseNodeGeneric<int> { }
//Generates an error
//class Node2 : BaseNodeGeneric<T> {}
//Generates an error
//class Node3 : T {}
從開放式構(gòu)造類型繼承的泛型類必須為任何未被繼承類共享的基類類型參數(shù)提供類型變量,如以下代碼所示:
class BaseNodeMultiple<T, U> { }
//No error
class Node4<T> : BaseNodeMultiple<T, int> { }
//No error
class Node5<T, U> : BaseNodeMultiple<T, U> { }
//Generates an error
//class Node6<T> : BaseNodeMultiple<T, U> {}
從開放式構(gòu)造類型繼承的泛型類必須指定約束,這些約束是基類型約束的超集或暗示基類型約束:
class NodeItem<T> where T : System.IComparable<T>, new() { }
class SpecialNodeItem<T> : NodeItem<T> where T : System.IComparable<T>, new() { }
泛型類型可以使用多個類型參數(shù)和約束,如下所示:
class SuperKeyType<K, V, U>
where U : System.IComparable<U>
where V : new()
{ }
開放式構(gòu)造類型和封閉式構(gòu)造類型可以用作方法參數(shù):
void Swap<T>(List<T> list1, List<T> list2)
{
//code to swap items
}
void Swap(List<int> list1, List<int> list2)
{
//code to swap items
}
如果某個泛型類實現(xiàn)了接口,則可以將該類的所有實例強制轉(zhuǎn)換為該接口。
泛型類是不變的。也就是說,如果輸入?yún)?shù)指定 List<BaseClass>,則當(dāng)您嘗試提供 List<DerivedClass> 時,將會發(fā)生編譯時錯誤。
泛型接口
為泛型集合類或表示集合中項的泛型類定義接口通常很有用。對于泛型類,使用泛型接口十分可取,例如使用 IComparable<T> 而不使用 IComparable,這樣可以避免值類型的裝箱和取消裝箱操作。.NET Framework 類庫定義了若干泛型接口,以用于 System.Collections.Generic 命名空間中的集合類。
將接口指定為類型參數(shù)的約束時,只能使用實現(xiàn)此接口的類型。下面的代碼示例顯示從 SortedList<T> 類派生的 GenericList<T> 類。
SortedList<T> 添加約束 where T : IComparable<T>。這將使 SortedList<T> 中的 BubbleSort 方法能夠?qū)α斜碓厥褂梅盒?CompareTo 方法。在此示例中,列表元素為簡單類,即實現(xiàn) Person 的 IComparable<Person>。
//Type parameter T in angle brackets.
public class GenericList<T> : System.Collections.Generic.IEnumerable<T>
{
protected Node head;
protected Node current = null;
// Nested class is also generic on T
protected class Node
{
public Node next;
private T data; //T as private member datatype
public Node(T t) //T used in non-generic constructor
{
next = null;
data = t;
}
public Node Next
{
get { return next; }
set { next = value; }
}
public T Data //T as return type of property
{
get { return data; }
set { data = value; }
}
}
public GenericList() //constructor
{
head = null;
}
public void AddHead(T t) //T as method parameter type
{
Node n = new Node(t);
n.Next = head;
head = n;
}
// Implementation of the iterator
public System.Collections.Generic.IEnumerator<T> GetEnumerator()
{
Node current = head;
while (current != null)
{
yield return current.Data;
current = current.Next;
}
}
// IEnumerable<T> inherits from IEnumerable, therefore this class
// must implement both the generic and non-generic versions of
// GetEnumerator. In most cases, the non-generic method can
// simply call the generic method.
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class SortedList<T> : GenericList<T> where T : System.IComparable<T>
{
// A simple, unoptimized sort algorithm that
// orders list elements from lowest to highest:
public void BubbleSort()
{
if (null == head || null == head.Next)
{
return;
}
bool swapped;
do
{
Node previous = null;
Node current = head;
swapped = false;
while (current.next != null)
{
// Because we need to call this method, the SortedList
// class is constrained on IEnumerable<T>
if (current.Data.CompareTo(current.next.Data) > 0)
{
Node tmp = current.next;
current.next = current.next.next;
tmp.next = current;
if (previous == null)
{
head = tmp;
}
else
{
previous.next = tmp;
}
previous = tmp;
swapped = true;
}
else
{
previous = current;
current = current.next;
}
}
} while (swapped);
}
}
// A simple class that implements IComparable<T> using itself as the
// type argument. This is a common design pattern in objects that
// are stored in generic lists.
public class Person : System.IComparable<Person>
{
string name;
int age;
public Person(string s, int i)
{
name = s;
age = i;
}
// This will cause list elements to be sorted on age values.
public int CompareTo(Person p)
{
return age - p.age;
}
public override string ToString()
{
return name + ":" + age;
}
// Must implement Equals.
public bool Equals(Person p)
{
return (this.age == p.age);
}
}
class Program
{
static void Main()
{
//Declare and instantiate a new generic SortedList class.
//Person is the type argument.
SortedList<Person> list = new SortedList<Person>();
//Create name and age values to initialize Person objects.
string[] names = new string[]
{
"Franscoise",
"Bill",
"Li",
"Sandra",
"Gunnar",
"Alok",
"Hiroyuki",
"Maria",
"Alessandro",
"Raul"
};
int[] ages = new int[] { 45, 19, 28, 23, 18, 9, 108, 72, 30, 35 };
//Populate the list.
for (int x = 0; x < 10; x++)
{
list.AddHead(new Person(names[x], ages[x]));
}
//Print out unsorted list.
foreach (Person p in list)
{
System.Console.WriteLine(p.ToString());
}
System.Console.WriteLine("Done with unsorted list");
//Sort the list.
list.BubbleSort();
//Print out sorted list.
foreach (Person p in list)
{
System.Console.WriteLine(p.ToString());
}
System.Console.WriteLine("Done with sorted list");
}
}
可將多重接口指定為單個類型上的約束,如下所示:
class Stack<T> where T : System.IComparable<T>, IEnumerable<T>
{
}
一個接口可定義多個類型參數(shù),如下所示:
interface IDictionary<K, V>
{
}
適用于類的繼承規(guī)則同樣適用于接口:
interface IMonth<T> { }
interface IJanuary : IMonth<int> { } //No error
interface IFebruary<T> : IMonth<int> { } //No error
interface IMarch<T> : IMonth<T> { } //No error
//interface IApril<T> : IMonth<T, U> {} //Error
如果泛型接口為逆變的,即僅使用其類型參數(shù)作為返回值,則此泛型接口可以從非泛型接口繼承。在 .NET Framework 類庫中,IEnumerable<T> 從 IEnumerable 繼承,因為 IEnumerable<T> 只在 GetEnumerator 的返回值和 Current 屬性 getter 中使用 T。
具體類可以實現(xiàn)已關(guān)閉的構(gòu)造接口,如下所示:
interface IBaseInterface<T> { }
class SampleClass : IBaseInterface<string> { }
只要類參數(shù)列表提供了接口必需的所有參數(shù),泛型類便可以實現(xiàn)泛型接口或已關(guān)閉的構(gòu)造接口,如下所示:
interface IBaseInterface1<T> { }
interface IBaseInterface2<T, U> { }
class SampleClass1<T> : IBaseInterface1<T> { } //No error
class SampleClass2<T> : IBaseInterface2<T, string> { } //No error
上一篇:使用C#發(fā)送帶附件的電子郵件的方法的代碼示例分析
欄 目:C#教程
下一篇:結(jié)合.net框架在C#派生類中觸發(fā)基類事件及實現(xiàn)接口事件
本文標(biāo)題:深入解析C#中的泛型類與泛型接口
本文地址:http://www.jygsgssxh.com/a1/C_jiaocheng/6720.html
您可能感興趣的文章
- 01-10深入淺出23種設(shè)計模式
- 01-10C#中查找Dictionary中的重復(fù)值的方法
- 01-10C#將圖片存放到SQL SERVER數(shù)據(jù)庫中的方法
- 01-10關(guān)于nancy中的身份驗證
- 01-10C#中的事務(wù)用法實例分析
- 01-10C#實現(xiàn)讀取DataSet數(shù)據(jù)并顯示在ListView控件中的方法
- 01-10C#中的正則表達(dá)式介紹
- 01-10C#開發(fā)中的垃圾回收機制簡析
- 01-10C#語言中的修飾符匯總
- 01-10C#中的 == 和equals()區(qū)別淺析


閱讀排行
本欄相關(guān)
- 01-10C#通過反射獲取當(dāng)前工程中所有窗體并
- 01-10關(guān)于ASP網(wǎng)頁無法打開的解決方案
- 01-10WinForm限制窗體不能移到屏幕外的方法
- 01-10WinForm繪制圓角的方法
- 01-10C#實現(xiàn)txt定位指定行完整實例
- 01-10WinForm實現(xiàn)仿視頻播放器左下角滾動新
- 01-10C#停止線程的方法
- 01-10C#實現(xiàn)清空回收站的方法
- 01-10C#通過重寫Panel改變邊框顏色與寬度的
- 01-10C#實現(xiàn)讀取注冊表監(jiān)控當(dāng)前操作系統(tǒng)已
隨機閱讀
- 01-11ajax實現(xiàn)頁面的局部加載
- 08-05織夢dedecms什么時候用欄目交叉功能?
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 01-10使用C語言求解撲克牌的順子及n個骰子
- 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
- 01-10delphi制作wav文件的方法
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 04-02jquery與jsp,用jquery
- 01-10C#中split用法實例總結(jié)
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置


