简体   繁体   English

将派生类作为基类泛型类返回

[英]Returning derived class as base generic class

I'm writing unity scripts on C#. 我在C#上编写统一脚本。 I've got my base class: 我有我的基类:

BaseMonoBehavior<T> : MonoBehaviour where T : BasePresenter

Some scripts extend this class, fe: 有些脚本扩展了这个类,fe:

MyMonoBehaviour : BaseMonoBehaviour<MyPresenter> 
// MyPresenter extends BasePresenter

Then I have a type class with method, which adds this scripts as components to GameObject according to it's value: 然后我有一个带有方法的类型类,它根据它的值将这些脚本作为组件添加到GameObject:

void addComponentTo(GameObject gameObject) {
    if (myType == TYPE_A) {
        var script = gameObject.AddComponent<MyMonoBehaviour>();
    }
}

It's okay, but what can I do, if I want to return created script as base class? 没关系,但如果我想将创建的脚本作为基类返回,我该怎么办? I want but can't write something like this: 我想但不能写这样的东西:

BaseMonoBehaviour addComponentTo(GameObject gameObject) {
    if (myType == TYPE_A) {
        var script = gameObject.AddComponent<MyMonoBehaviour>();
        return script;
    }
    return null;
}

So, my question is simple - how can I do this? 所以,我的问题很简单 - 我该怎么做? I want to use some methods of base class in the method, which calls addComponentTo ... 我想在方法中使用一些基类方法,它调用addComponentTo ...

PS Afterwards I'd like to get MyMonoBehaviour as BaseMonoBehaviour from GameObject , if it's possible, but it's yet another question. PS后来我想从游戏对象得到MyMonoBehaviourBaseMonoBehaviour,如果这是可能的,但它是另一个问题。

Since BaseMonoBehaviour is generic on a presenter class, you could make AddComponentTo generic as well: 由于BaseMonoBehaviour在presenter类上是通用的,因此您也可以将AddComponentTo泛型:

BaseMonoBehaviour<TP> AddComponentTo(GameObject gameObject) where TP : BasePresenter {
    if (myType == TYPE_A) {
        var script gameObject.AddComponent<MyMonoBehaviour>();
        return script;
    }
    return null;
}

Then the caller would be able to call it as follows: 然后调用者可以按如下方式调用它:

var component = AddComponentTo<MyPresenter>(gObj);

This requires all generic instances returned by AddComponentTo to be generic on the same type that you can specify at invocation point. 这要求AddComponentTo返回的所有泛型实例在您可以在调用点指定的相同类型上是通用的。

Note: If AddComponentTo creates generic instances that are generic on the same presenter, you could even make it non-generic, like this: 注意:如果AddComponentTo在同一个演示者上创建通用的通用实例,您甚至可以将其设置为非泛型,如下所示:

BaseMonoBehaviour<MyPresenter> AddComponentTo(GameObject gameObject) {
    if (myType == TYPE_A) {
        var script gameObject.AddComponent<MyMonoBehaviour>();
        return script;
    }
    return null;
}

and call it like this: 并称之为:

var component = AddComponentTo(gObj);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM