簡體   English   中英

從System.Type變量創建類的實例

[英]Creating instance of class from System.Type variable

我正在嘗試在XNA中構建一個簡單的游戲引擎,其靈感來自Unity。 我目前正在研究的是可以附加到游戲對象的組件。 我有像“PlayerController”和“Collider”這樣的類,它們是組件,因此繼承自Component類。

我正在嘗試創建方法,而不是根據Type參數添加新組件,例如在嘗試需要組件時:

public void RequireComponent(System.Type type)
{
    //Create the component
    Component comp = new Component();
    //Convert the component to the requested type
    comp = (type)comp; // This obviously doesn't work
    //Add the component to the gameobject
    gameObject.components.Add(comp);
}

例如,剛體組件需要游戲對象具有碰撞器,因此它需要碰撞器組件:

public override void Initialize(GameObject owner)
{
    base.Initialize(owner);

    RequireComponent(typeof(Collider));
}

可以這樣做還是有更好的方法?

public void RequireComponent(System.Type type)
{
    var comp = (Component)Activator.CreateInstance(type, new object[]{});

    gameObject.components.Add(comp);
}

但是,如果您發現自己傳遞編譯時常量,例如typeof(Collider) ,您可能會這樣做:

public void Require<TComponent>() where TComponent : class, new()
{
    gameObject.components.Add(new TComponent());
}

並稱之為:

Require<Collider>();

而不是第一個版本:

RequireComponent(typeof(Collider));

要回答您的問題,在給定Type對象時獲取對象的最簡單方法是使用Activator類:

public void RequireComponent(System.Type type)
{
    var params = ; // Set all the parameters you might need in the constructor here
    var component = (typeof(type))Activator.CreateInstance(typeof(type), params.ToArray());
    gameObject.components.Add(component);
}

但是,我認為這可能是一個XY問題 據我所知,這是您在游戲引擎中實現模塊化的解決方案。 你確定這是你想要的嗎? 我建議您在決定方法之前花一些時間閱讀多態性和相關概念,以及如何在C#中應用這些概念。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM