从 System.Type 变量创建 class 的实例
Creating instance of class from System.Type variable
我正在尝试在受 Unity 启发的 XNA 中构建一个简单的游戏引擎。我目前正在研究的是可以附加到游戏对象的组件。我有 class 像 "PlayerController" 和 "Collider" 这样的组件,因此继承自组件 class。
我正在尝试创建可以根据 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);
}
比如rigidbody组件需要gameobject有collider,所以需要collider组件:
public override void Initialize(GameObject owner)
{
base.Initialize(owner);
RequireComponent(typeof(Collider));
}
可以这样做吗,或者有更好的方法吗?
为了回答您的问题,在给定 Type
对象时获取对象的最简单方法是使用 Activator class:
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 problem。据我了解,这是您在游戏引擎中实现模块化的解决方案。但是,您确定这就是您想要的方式吗?我的建议是,在决定您的方法之前,花一些时间阅读多态性和相关概念,以及如何在 C# 中应用这些概念。
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));
我正在尝试在受 Unity 启发的 XNA 中构建一个简单的游戏引擎。我目前正在研究的是可以附加到游戏对象的组件。我有 class 像 "PlayerController" 和 "Collider" 这样的组件,因此继承自组件 class。
我正在尝试创建可以根据 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);
}
比如rigidbody组件需要gameobject有collider,所以需要collider组件:
public override void Initialize(GameObject owner)
{
base.Initialize(owner);
RequireComponent(typeof(Collider));
}
可以这样做吗,或者有更好的方法吗?
为了回答您的问题,在给定 Type
对象时获取对象的最简单方法是使用 Activator class:
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 problem。据我了解,这是您在游戏引擎中实现模块化的解决方案。但是,您确定这就是您想要的方式吗?我的建议是,在决定您的方法之前,花一些时间阅读多态性和相关概念,以及如何在 C# 中应用这些概念。
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));