Tの一般的な制約は、参照タイプと値タイプに同時にですか?
-
09-10-2019 - |
質問
一般的な制約がどのように機能するかを理解することに問題があります。ここで何か重要なものが欠けていると思います。私はコメントに私の質問を同封しました、そして、いくつかの説明を提供してくれたことに感謝するでしょう。
//1st example:
class C <T, U>
where T : class
where U : struct, T
{
}
//Above code compiles well,
//On first sight it looks like U might be reference type and value type
//at the same time. The only reason I can think of, is that T may be an
//interface which struct can implement, Am I correct?
//2nd example
class CC<T, U>
where T : class, new ()
where U : struct, T
{
}
//I added also a reguirement for parameterless constructor
//and, much to my surprise, it still compiles what is
//a bit inexplicable for me.
//What 'U' would meet the requirement to be
//value type, reference type and have a contructor at the same time?
解決
それは何の問題もありません。の定義を見てみましょう タイプパラメーターの制約:
T : class
- タイプ引数tは、クラス、インターフェイス、デリゲート、または配列タイプを含む参照タイプでなければなりません。U : struct
- タイプ引数uは値タイプでなければなりません。U : T
- タイプの引数uは、クラスTから派生する必要があります。
したがって、あなたがする必要があるのは、参照タイプに由来する値タイプを見つけることだけです。最初は不可能に聞こえるかもしれませんが、少し難しいと思うなら、すべての構造体がクラスに由来することを覚えているでしょう object
, 、したがって、これは両方の例で正常に機能します。
new C<object, int>();
ただし、交換する場合 struct
と class
その後、それはコンパイルされません:
// Error - Type parameter 'T' has the 'struct' constraint so 'T'
// cannot be used as a constraint for 'U'
class C<T, U>
where T : struct
where U : class, T
{
}
所属していません StackOverflow