4

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
4

2 に答える 2

2

いいえ、申告側ではできません。structまたはのいずれかclassです。ただし、typeof(T)実行時に をチェックしTて、Nullable<T2>

Type type = typeof(T);
if(Nullable.GetUnderlyingType(type) == null)
    throw new Exception();
于 2015-02-11T11:15:44.587 に答える