我一直在研究基于組件的系統的想法。想象一下,我讓它們像這樣:
public class CObject
{
public Component[] components;
public T GetComponent<T>(string name = string.empty)
{
foreach(var c in components) if(c is T) if(name != string.empty || c.name == name) return c as T;
}
}
然后我們將能夠從腳本中獲取組件,如下所示:
// ... some code
DragonComponent dragonComponent = dragonObject.GetComponent<DragonComponent>();
// some code ...
但正如你所看到的,每次呼叫都需要裝箱......我可以通過為以前的呼叫制作一個靜態字典來提高效率,如果給出了類似的呼叫,我可以讓它只使用字典。但是,它仍然非常混亂且效率不高......
我聽說過類似工會的結構,GetComponent可以像這樣實作:
public class CObject
{
private class CTypes {
public DragonComponent[] dragonComponents;
public CameraFocus[] cameraFocuses;
}
CTypes components;
public T GetComponent<T>()
{
switch(T)
{
case DragonComponent: return components.dragonComponents[0];
case CameraFocus: return components.cameraFocuses[0];
}
}
}
這是超級性能但很難實作......我不知道如何在類似聯合的結構中自動化創建新型別的程序。
最好的方法是什么?
感謝:D
uj5u.com熱心網友回復:
看起來您正在嘗試實作自己的IoC框架。有很多依賴注入框架。甚至內置于 ASP.NET Core。
如果這對您來說太過分了,那么對于您的情況,還有許多更簡單的替代方案。首先,您可能會想到字典:
private static readonly Dictionary<Type, object> _components = new();
public T GetComponent<T>() => (T)_components[typeof(T)];
或者,性能更高,使用靜態泛型類:
private class ComponentCache<T>
{
public static readonly T Component { get; set; }
}
public T GetComponent<T>() => ComponentCache<T>.Component;
此外,裝箱僅適用于值型別。無論哪種方式,相信我,對于您作為初學者現在正在撰寫的任何小程式來說,性能影響都可以忽略不計。
這些不是完整的例子,但我希望能給你一些指導。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/333938.html
