简体   繁体   English

在父类型的方法中返回子 class

[英]Return child class in a method of parent type

I am using a component system for certain Objects(just like components in Unity).我正在为某些对象使用组件系统(就像 Unity 中的组件一样)。 Each component inheriths from the class Component .每个组件都继承自 class组件 The objects then have a list of components.然后这些对象有一个组件列表。

What I am trying to implement is a GetComponent() method.我想要实现的是一个GetComponent()方法。 It returns the component of type T if it exists, otherwise it returns null.如果存在则返回类型T的组件,否则返回 null。 Let's say that an Object has the Renderer Component.假设 Object 具有渲染器组件。 I want to be able to call the Draw method in the Renderer class:我希望能够在渲染器 class 中调用 Draw 方法:

Object.GetComponent<Renderer>().Draw();

The problem is that when I call this function I get the parent class(of type: Component ) instead of the child class.问题是当我调用这个 function 时,我得到了父类(类型: Component )而不是子类 class。 Because of that, when I try the code above ^^ I get the error;因此,当我尝试上面的代码时 ^^ 我得到了错误; 'Component' does not contain a definition for 'Draw' (...) “组件”不包含“绘图”的定义(...)

Code:代码:

internal abstract class GameObject : Object
{
    //Props
    public string name;
    public GameObject? parent;
    public Transform transform 
    {
        get 
        {
            return (parent == null) ? transform : parent.transform;
        }
        private set 
        {
            transform = value;
        }
    }

    public bool isActive = true;

    private List<Component> components = new List<Component>();

    //Constructer
    public GameObject(string name, GameObject? parent = null)
    {
        this.name = name;
        
        transform = new Transform(this);
        components.Add(transform);

        this.parent = parent;
    }

    public void AddComponent(Component component)
    {
        components.Add(component);
    }

    //Method that is not working properly
    public Component GetComponent<T>()
    {
        foreach (Component component in components)
        {
            if (typeof(T) == component.GetType())
                return component;
        }
        return null;
    }
}

} }

The return value of the method needs to be T方法的返回值需要是T

public T GetComponent<T>()
{
    // your code
}

GetComponent<Renderer>().Draw() is 2 statements GetComponent<Renderer>().Draw()是 2 个语句

  1. GetComponent<Renderer>()
  2. Draw()

By writing it like so:通过这样写:

// 'component' is of type 'Component' here, not 'Renderer'
var component = GetComponent<Renderer>();
component.Draw();

It's obvious why it doesn't work with your current code and why it does with the updated one.很明显为什么它不适用于您当前的代码以及为什么它适用于更新的代码。


PS I'd personally also add a constraint to make sure we can only GetComponent<T> with types that actually are components, like so: PS 我个人还会添加一个约束,以确保我们只能GetComponent<T>使用实际上是组件的类型,如下所示:

public T GetComponent<T>() where T : Component
{

}

With the where we're forcing compile time checks that this method can only be called with types that inherit from Component where我们强制编译时检查该方法只能使用从Component继承的类型调用

Instead of returning Component , return T .不是返回Component ,而是返回T Also, use is for type checking and casting:此外, is类型检查和强制转换:

public T GetComponent<T>() where T : Component
{
    foreach(var component in components)
    {
        if(component is T value) return value;
    }
    return default;
}

BTW, what if you have two components of the same type?顺便说一句,如果您有两个相同类型的组件怎么办? You might want to consider using Linq's OfType<T>() here instead of a foreach .您可能需要考虑在这里使用 Linq 的OfType<T>()而不是foreach

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

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