端くれプログラマの備忘録 C# [C#] ジェネリック

[C#] ジェネリック

  • C# 2.0: 実装
  • C# 4.0: 共変性・反変性
  • C# 7.3: 制約条件追加 (unmanaged, Enum, Delegate)
  • C #8.0: 制約条件追加 (notnull)

ジェネリックメソッド

記法

アクセスレベル 戻り値の型 メソッド名<型引数>(引数リスト)
  where 型引数中の型が満たすべき条件
{
  メソッド定義
}

public static Type Max<Type>(Type a, Type b)
    where Type : IComparable
{
    return a.CompareTo(b) > 0 ? a : b;
}

int n1 = Max<int>(5, 10);
int n2 = Max(5, 10);
double x = Max(5.0, 10.0);
string s = Max("abc", "cat");

ジェネリッククラス

記法

class クラス名<型引数>
  where 型引数中の型が満たすべき条件
{
  クラス定義
}

class Stack<Type>
{
    Type[] buf;
    int top;
    public Stack(int max) { this.buf = new Type[max]; this.top = 0; }
    public void Push(Type val) { this.buf[this.top++] = val; }
    public Type Pop() { return this.buf[--this.top]; }
    public int Size { get { return this.top; } }
    public int MaxSize { get { return this.buf.Length; } }
}

const int SIZE = 5;
Stack<int> si = new Stack<int>(SIZE);
Stack<double> sd = new Stack<double>(SIZE);

for (int i = 1; i <= SIZE; ++i)
{
    si.Push(i);
    sd.Push(1.0/i);
}
while (si.Size != 0)
{
    Console.WriteLine("1/{0} = {1}", si.Pop(), sd.Pop());
}

参考サイト

ジェネリック – C# によるプログラミング入門 | ++C++; // 未確認飛行 C
https://ufcpp.net/study/csharp/sp2_generics.html