最終更新:2015-04-28 (火) 01:29:08 (2952d)
ジェネリック
Top / ジェネリック
C++ で言うところの template。“型をパラメータに持つ型”を作ることが出来ます。
Tというのは仮の型。なんでもいい
VB.NET/ジェネリック?
'宣言 Public Class Generic(Of T) Public Field As T End Class '使う Dim g As New Generic(Of String) g.Field = "A string"
C♯/ジェネリック
//宣言 public class Generic<T> { public T Field; } //使う Generic<string> g = new Generic<string>(); g.Field = "A string";
- 実行時エラーがコンパイル時に分かる
- 型がわかるのでIntelliSenseでコーディング中の補完が楽になる
Dim list As New System.Collections.ArrayList() ↓ //ArrayListクラスのジェネリック対応版 Dim list As New System.Collections.Generic.List(Of String)
ジェネリッククラス (System.Collections.Generic)
- System.Collections.Generic.Dictionary(Of TKey, TValue)
- System.Collections.Generic.List(Of T)
- System.Collections.Generic.LinkedList?(Of T)
- System.Collections.Generic.Queue(Of T)
- System.Collections.Generic.SortedDictionary?(Of TKey, TValue)
- System.Collections.Generic.SortedList?(Of TKey, TValue)
- System.Collections.Generic.Stack?(Of T)
Dim words() As String = { "the", "fox", "jumped", "over", "the", "dog" } Dim sentence As New LinkedList(Of String)(words)//初期値にwordを渡す
キーワード
- 型パラメータ?
C++
template<typename T> void Swap(T & a, T & b) //"&"により参照としてパラメーターを渡している。 { T temp = b; b = a; a = temp; } string hello = "world!", world = "Hello, "; Swap( world, hello ); cout << hello << world << endl; //出力は"Hello, world!"
- 演算子のオーバーロードと組み合わせると便利。
template <typename T> T max(T x, T y) { if (x < y) return y; else return x; }