在 C# 中使用嵌套泛型类时的继承问题 [英] Issue with Inheritance when using nested Generic classes in C#
问题描述
我正在尝试创建一个类层次结构,以便我可以拥有:
I'm trying to create a class hierarchy such that I can have:
SpecificScreenController
屏幕控制器单身
SpecificScreenController < ScreenController < Singleton
到目前为止,我已将这些设置为:
So far I have these set up as:
public abstract class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static T _instance;
public static T Instance{ get{... return _instance;} }
}
public abstract class ScreenController<T> : Singleton<T> where T : MonoBehaviour
{
public GAME_SCREEN GameScreen;
//many more ScreenController common properties/fields/methods
}
public class SpecificScreenController : ScreenController<SpecificScreenController>
{
//subclass specific properties, overriden ScreenController methods etc.
}
这样我就可以使用 SpecificScreenController.Instance.GameScreen;
到目前为止,这很好用.
This way I can use SpecificScreenController.Instance.GameScreen;
This works, so far, so good.
我现在想要做的是,例如:
What I want to now do with this is, for instance:
List<ScreenController> screenControllers = new List<ScreenController>();
screenControllers.Add(SpecificScreenController.Instance);
ScreenController s = screenControllers.Find(i => i.GameScreen == GAME_SCREEN.THING);
但是,当然......这不会编译,因为 ScreenController
现在需要一个通用类型等.我可以/应该使用什么习语来保留单例行为和 ScreenController 子/超类?
But, of course ... this won't compile because ScreenController
now requires a Generic Type etc. What idiom can/should I use to preserve the Singleton behavior and ScreenController sub/superclasses ?
推荐答案
由于这个问题似乎没有真正干净的解决方案,我最终从我的类层次结构中删除了单例,并复制粘贴了单例属性的非通用版本获取/实例化代码到我想要成为单例的每个类中.
As there seem to be no really clean solutions to this issue I ended up removing Singleton from my class hierarchy and copy-pasted non-generic versions of the singleton property get/instantiate code into each of the classes that I wanted to be singletons.
public abstract class ScreenController : MonoBehaviour
{
}
public class SpecificScreenController : ScreenController
{
private static SpecificScreenController _instance;
public static SpecificScreenController Instance{ get{... return _instance;}
}
这篇关于在 C# 中使用嵌套泛型类时的继承问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!