繁体   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