[英]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.