C# 泛型
泛型類別和方法將重複使用性、型別安全和高效率三者結合在一起,發揮了非泛型的類別和方法所無法提供的功能。泛型最常搭配在這種型別上操作的集合和方法使用。.NET Framework 2.0 版類別庫提供了新的命名空間 System.Collections.Generic,其中包含多個以泛型為基礎的新集合類別。一般建議,使用 2.0 版的所有應用程式都應使用新的泛型集合類別,而不要使用舊版的非泛型對應類別,例如 ArrayList。如需詳細資訊,請參閱 .NET Framework 類別庫中的泛型 (C# 程式設計手冊)。
當然,您也可以建立自訂的泛型型別和方法,自行處理泛型化的問題,並設計型別安全而且效率高的模式。在下列程式碼中,示範了一個簡單的泛型連結清單類別 (在大部分情況下,會建議您使用 .NET Framework 類別庫提供的 List<T> 類別,而不要自行建立類別)。這個範例在幾處使用了型別參數 T,這些地方通常需要使用具象型別來表示清單中儲存的項目型別。這個參數可以用於:
-
做為 AddHead 方法中的方法參數型別。
-
做為公用方法 GetNext 的傳回型別,以及巢狀 Node 類別中的 Data 屬性。
-
做為巢狀類別中私用成員資料的型別。
請注意,T 可用於巢狀 Node 類別。當 GenericList<T> 以具象型別執行個體化時,例如執行個體化為 GenericList<int>,則每次出現的 T 項目都會被 int 取代。
// type parameter T in angle brackets
public class GenericList<T>
{
// The nested class is also generic on T
private class Node
{
// T used in non-generic constructor
public Node(T t)
{
next = null;
data = t;
}
private Node next;
public Node Next
{
get { return next; }
set { next = value; }
}
// T as private member data type
private T data;
// T as return type of property
public T Data
{
get { return data; }
set { data = value; }
}
}
private Node head;
// constructor
public GenericList()
{
head = null;
}
// T as method parameter type:
public void AddHead(T t)
{
Node n = new Node(t);
n.Next = head;
head = n;
}
public IEnumerator<T> GetEnumerator()
{
Node current = head;
while (current != null)
{
yield return current.Data;
current = current.Next;
}
}
}
下列程式碼範例示範用戶端程式碼如何使用泛型 GenericList<T> 類別建立整數清單。您只要變更型別引數,就能輕鬆修改下面的程式碼來建立字串清單或其他任何自訂型別的清單:
class TestGenericList
{
static void Main()
{
// int is the type argument
GenericList<int> list = new GenericList<int>();
for (int x = 0; x < 10; x++)
{
list.AddHead(x);
}
foreach (int i in list)
{
System.Console.Write(i + " ");
}
System.Console.WriteLine("\nDone");
}
}
===================================泛型集合类================================
泛型最常见的用途是泛型集合,命名空间System.Collections.Generic 中包含了一些基于泛型的集合类,使用泛型集合类可以提供更高的类型安全性,还有更高的性能,避免了非泛型集合的重复的装箱和拆箱。
很多非泛型集合类都有对应的泛型集合类,下面是常用的非泛型集合类以及对应的泛型集合类:
| 非泛型集合类 | 泛型集合类 |
| ArrayList | List<T> |
| HashTable | DIctionary<T> |
| Queue | Queue<T> |
| Stack | Stack<T> |
| SortedList | SortedList<T> |
我们用的比较多的非泛型集合类主要有 ArrayList类 和 HashTable类。我们经常用HashTable 来存储将要写入到数据库或者返回的信息,在这之间要不断的进行类型的转化,增加了系统装箱和拆箱的负担,如果我们操纵的数据类型相对确定的化 用 Dictionary<TKey,TValue> 集合类来存储数据就方便多了,例如我们需要在电子商务网站中存储用户的购物车信息( 商品名,对应的商品个数)时,完全可以用 Dictionary<string, int> 来存储购物车信息,而不需要任何的类型转化。
下面是简单的例子,包括声明,填充键值对,移除键值对,遍历键值对
Dictionary<string, string> myDic = new Dictionary<string, string>();
myDic.Add("aaa", "111");
myDic.Add("bbb", "222");
myDic.Add("ccc", "333");
myDic.Add("ddd", "444");
//如果添加已经存在的键,add方法会抛出异常
try
{
myDic.Add("ddd","ddd");
}
catch (ArgumentException ex)
{
Console.WriteLine("此键已经存在:" + ex.Message);
}
//解决add()异常的方法是用ContainsKey()方法来判断键是否存在
if (!myDic.ContainsKey("ddd"))
{
myDic.Add("ddd", "ddd");
}
else
{
Console.WriteLine("此键已经存在:");
}
//而使用索引器来负值时,如果建已经存在,就会修改已有的键的键值,而不会抛出异常
myDic ["ddd"]="ddd";
myDic["eee"] = "555";
//使用索引器来取值时,如果键不存在就会引发异常
try
{
Console.WriteLine("不存在的键\"fff\"的键值为:" + myDic["fff"]);
}
catch (KeyNotFoundException ex)
{
Console.WriteLine("没有找到键引发异常:" + ex.Message);
}
//解决上面的异常的方法是使用ContarnsKey() 来判断时候存在键,如果经常要取健值得化最好用 TryGetValue方法来获取集合中的对应键值
string value = "";
if (myDic.TryGetValue("fff", out value))
{
Console.WriteLine("不存在的键\"fff\"的键值为:" + value );
}
else
{
Console.WriteLine("没有找到对应键的键值");
}
//下面用foreach 来遍历键值对
//泛型结构体 用来存储健值对
foreach (KeyValuePair<string, string> kvp in myDic)
{
Console.WriteLine("key={0},value={1}", kvp.Key, kvp.Value);
}
//获取值得集合
foreach (string s in myDic.Values)
{
Console.WriteLine("value={0}", s);
}
//获取值得另一种方式
Dictionary<string, string>.ValueCollection values = myDic.Values;
foreach (string s in values)
{
Console.WriteLine("value={0}", s);
}常用的属性和方法如下:
| | | |
| 获取用于确定字典中的键是否相等的 IEqualityComparer。 | ||
| | 获取包含在 Dictionary 中的键/值对的数目。 | |
| | 获取或设置与指定的键相关联的值。 | |
| | 获取包含 Dictionary 中的键的集合。 | |
| | 获取包含 Dictionary 中的值的集合。 | |
| 常用的方法 | 方法说明 | |
| | 将指定的键和值添加到字典中。 | |
| | 从 Dictionary 中移除所有的键和值。 | |
| | 确定 Dictionary 是否包含指定的键。 | |
| | 确定 Dictionary 是否包含特定值。 | |
| | ||
| | 返回循环访问 Dictionary 的枚举数。 | |
| | 用作特定类型的哈希函数。GetHashCode 适合在哈希算法和数据结构(如哈希表)中使用。 (从 Object 继承。) | |
| | 实现 System.Runtime.Serialization.ISerializable 接口,并返回序列化 Dictionary 实例所需的数据。 | |
| | ||
| | 实现 System.Runtime.Serialization.ISerializable 接口,并在完成反序列化之后引发反序列化事件。 | |
| | 确定指定的 Object 实例是否是相同的实例。 (从 Object 继承。) | |
| | 从 Dictionary 中移除所指定的键的值。 | |
| | ||
| | 获取与指定的键相关联的值。 |

浙公网安备 33010602011771号