LoginSignup
17
21

More than 5 years have passed since last update.

ジェネリックの型パラメータの制約

Posted at
制約なし
class Test<T> {
    public T obj;

    public Test() {
        obj = default(T);
    }
}
基本クラス制約
class Test<T> where T : 基本クラス名 {
}

// 2つの型パラメーターの関係を確立する制約
// VはTと同一かTから継承しなければならない.
class Test<T, V> where V : T {
}
参照型制約
class Test<T> where T : class {
    T obj;

    public Test() {
        obj = null;
    }
}
値型制約
class Test<T> where T : struct {
}
インターフェイス制約
class Test<T> where T : インターフェイス名 {
}
コンストラクター制約
class Test<T> where T : new() {
    T obj;

    public Test() {
        obj = new T();
    }
}
複数の制約を使用する
// 制約を指定する順番は下記の通りです。
// (基本クラス or class or struct), インターフェイス, new()
class Test<T> where T : MyClass, IMyInterface, new() {
}

// 複数のwhere句がある場合は、スペースで区切ります。
class Test2<T, V> where T : class where V : struct {
}
17
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
17
21