LoginSignup
6
5

More than 5 years have passed since last update.

【C#】enumを型制約で扱う

Posted at

ジェネリックの型制約

where句を使うと、型パラメータに制約をかけられる。

class MyClass1<T>
    where T : class     // TはクラスならなんでもOK
{
}

class MyClass2{}

class MyClass3<T>
    where T : MyClass2  // TはMyClass2、またはその派生クラス
{
}

複数指定する場合。

class MyClass1{}
class MyClass2{}

class MyClass1<T, U>
    where T : MyClass1
    where U : MyClass2
{
}

値型を型パラメータで扱う

class MyClass<T>
    where T : struct        // Tは値型
{
    private T m_param;
}

{
    MyClass<int> myClass = new MyClass<int>();
}

enumを型パラメータで扱う

enumは値型に含まれるので、intと同様に型制約の指定ができる。

class MyClass<T>
    where T : struct        // Tは値型
{
    private T m_param;
}

enum MyEnum
{
    INDEX0 = 0,
    INDEX1,
    INDEX2
}

{
    MyClass<MyEnum> myClass = new MyClass<MyEnum>();
    myClass.m_param = MyEnum.INDEX0;
}

## 参考サイト

where (ジェネリック型制約)
https://msdn.microsoft.com/ja-jp/library/bb384067.aspx

値型
https://msdn.microsoft.com/ja-jp/library/s1ax56ch.aspx

6
5
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
6
5