C#

C# ジェネリック(System.Collections.Generic名前空間)クラス

C# 非ジェネリック コレクションは使えない?」などで登場した「ジェネリック」なクラスですが、下記のクラスがあります。

List<T>
LinkedList<T>
Stack<T>
Queue<T>
Dictionary<TKey, TValue>
SortedDictionary<TKey, TValue>
SortedList<TKey, TValue>
HashSet<T>
SortedSet<T>

これらは、すべて System.Collections.Generic 名前空間のクラスです。

 

「ジェネリック」なクラスの宣言

この「ジェネリック」なクラスの宣言ですが、下記のように宣言されています。

public class List<T> : IList<T>, ICollection<T>, IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable
public class LinkedList<T> : ICollection<T>, IEnumerable<T>, ICollection, IEnumerable, ISerializable, IDeserializationCallback
public class Stack<T> : IEnumerable<T>, ICollection, IEnumerable
public class Queue<T> : IEnumerable<T>, ICollection, IEnumerable
public class Dictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IReadOnlyDictionary<TKey, TValue>, IReadOnlyCollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IEnumerable, ISerializable, IDeserializationCallback
public class SortedDictionary<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IEnumerable
public class SortedList<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, IDictionary, ICollection, IEnumerable
public class HashSet<T> : ISerializable, IDeserializationCallback, ISet<T>, ICollection<T>, IEnumerable<T>, IEnumerable
public class SortedSet<T> : ISet<T>, ICollection<T>, IEnumerable<T>, ICollection, IEnumerable, ISerializable, IDeserializationCallback

 

‘:’の右側は「基本クラス」で宣言しているクラスに必要なものを持っているクラスやインターフェースクラスです。

この宣言のコードだけ見ていると、すごくややこしく見えてしまいますが、ある程度の法則性があります。

 

ジェネリックなクラスの共通点

この「ジェネリック」なクラスの基本クラスは、大きく

  • IEnumerable、IEnumerable<>の派生クラスである
  • ICollectionもしくはICollection<>というクラスの派生クラスになっている

と言えます。
この2つ以外は、それぞれのクラスの機能によって異なる基本クラスから派生しています。

System.Collections.Genericのコレクションクラスは、ICollectionというコレクションの入れ物にデータを入れ、IEnumerableでコレクションを走査するという作りになっています。

 

タイトルとURLをコピーしました