1

我在 Unity3D(在 C# 中)工作,我在其中定义了这个泛型类:

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

这是其他类派生自的单例类型的模板。

MonoBehaviour类包含太多的字段和方法,所以为了避免返回的 Singleton 实例(类型为 T)过于混乱,我定义了以下类型:

/// <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