从System.Type变量创建类的实例

我试图在XNA中构建一个非常受Unity启发的简单游戏引擎。 我目前的工作是可以附加到gameobjects的组件。 我有像“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);
}

例如,刚体组件需要gameobject有一个collider,所以它需要碰撞组件:

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#。

链接地址: http://www.djcxy.com/p/95525.html

上一篇: Creating instance of class from System.Type variable

下一篇: XNA Load/Unload logic (contentmanager?)