Issue with Inheritance when using nested Generic classes in C#

最后都变了- 提交于 2020-01-28 11:28:13

问题


I'm trying to create a class hierarchy such that I can have:

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.
}

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);

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 ?


回答1:


The problem here is one of covariance. You're assuming that if SpecificScreenController inherits from MonoBehaviour then ScreenController<SpecificScreenController> also inherits from ScreenController<MonoBehaviour>. It doesn't. You can't do this cast.




回答2:


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;} 
}


来源:https://stackoverflow.com/questions/35445875/issue-with-inheritance-when-using-nested-generic-classes-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!