1

私は Unity3D (C#) で作業しています。そこでは、このジェネリック クラスが定義されています。

public class Singleton<T> : MonoBehaviour where T : MonoBehaviour

これは、他のクラスが派生するシングルトン型のテンプレートです。

MonoBehaviourクラスにはあまりにも多くのフィールドとメソッドが含まれているため、返された (T 型の) Singleton インスタンスが乱雑にならないように、次の型を定義しました

/// <summary>
/// A singleton implementation where the Instance property can return another type I (derived from T)
/// </summary>
public class Singleton<T, I> : Singleton<T> 
    where T : MonoBehaviour, I
{
    public static new I Instance
    {
        get
        {
            // Return the Instance property, cast as I
            return (I)Singleton<T>.Instance;
        }
    }
}

これはまったく問題ありませんが、次の新しい型定義ではコンパイラ エラーは発生しません。

public class SomeVideoProvider : Singleton<SomeVideoProvider, IVideoAds>
{
    // Why doesn't the compiler enforce this type to be derived from IVideoAds ?
}

一般的な制約は、T が MonoBehaviour と I の両方である必要があることを宣言します。この場合、それは満たされていませんが、コンパイラ エラーはありません。何故ですか ?

4

0 に答える 0