[英]Return child class in a method of parent type
我正在为某些对象使用组件系统(就像 Unity 中的组件一样)。 每个组件都继承自 class组件。 然后这些对象有一个组件列表。
我想要实现的是一个GetComponent()方法。 如果存在则返回类型T的组件,否则返回 null。 假设 Object 具有渲染器组件。 我希望能够在渲染器 class 中调用 Draw 方法:
Object.GetComponent<Renderer>().Draw();
问题是当我调用这个 function 时,我得到了父类(类型: Component )而不是子类 class。 因此,当我尝试上面的代码时 ^^ 我得到了错误; “组件”不包含“绘图”的定义(...)
代码:
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;
}
}
}
方法的返回值需要是T
public T GetComponent<T>()
{
// your code
}
GetComponent<Renderer>().Draw()
是 2 个语句
GetComponent<Renderer>()
Draw()
通过这样写:
// 'component' is of type 'Component' here, not 'Renderer'
var component = GetComponent<Renderer>();
component.Draw();
很明显为什么它不适用于您当前的代码以及为什么它适用于更新的代码。
PS 我个人还会添加一个约束,以确保我们只能GetComponent<T>
使用实际上是组件的类型,如下所示:
public T GetComponent<T>() where T : Component
{
}
where
我们强制编译时检查该方法只能使用从Component
继承的类型调用
不是返回Component
,而是返回T
。 此外, is
类型检查和强制转换:
public T GetComponent<T>() where T : Component
{
foreach(var component in components)
{
if(component is T value) return value;
}
return default;
}
顺便说一句,如果您有两个相同类型的组件怎么办? 您可能需要考虑在这里使用 Linq 的OfType<T>()
而不是foreach
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.