C#では、Nullable<T>
型は一般的な制約を満たしていませんwhere
struct
(AFAKは技術的には構造体です)。これを使用して、ジェネリック引数が null 非許容値型でなければならないことを指定できます。
T DoSomething<T>() where T : struct
{
//...
}
DoSomething<int?>(); //not ok
DoSomething<int>(); //ok
もちろん、参照型の制約Nullable<T>
も満たしていません。where
class
T DoSomething<T>() where T : class
{
//...
}
DoSomething<int?>(); //not ok
DoSomething<Foo>(); //ok
Nullable 値型ではなく、参照型または値型である必要があるなどの制約を定義することは可能ですか?
このようなもの :
void DoSomething<T>() where T : class, struct //wont compile!
{
//...
}
DoSomething<int?>(); //not ok
DoSomething<int>(); //ok
DoSomething<Foo>(); //ok