最終更新:2015-04-28 (火) 01:29:08 (3279d)  

ジェネリック
Top / ジェネリック

C++ で言うところの template。“型をパラメータに持つ型”を作ることが出来ます。

System.Collections.Generic

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)

Dim words() As String = { "the", "fox", "jumped", "over", "the", "dog" }
Dim sentence As New LinkedList(Of String)(words)//初期値にwordを渡す

キーワード

  • 型パラメータ?

C++

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;
}

Java

参考