从变量中获取一个类型并将其用作泛型方法的参数

时间:2017-07-22 23:09:43

标签: c# visual-studio generics xna game-engine

我正在为xna中的一个简单的游戏引擎工作,我将用于未来的项目。它的灵感来自Unity的框架。 我正在开发一个游戏对象&目前的组件系统已经卡在克隆游戏对象上。

这就是我尝试实施它的方式,

public static GameObject CloneGameObject(GameObject obj, Vector2 position, float scale)
{
    var clone = new GameObject(); //Create a entirely new gameobject
    foreach (var comp in obj.components) //Clone all the components
    {
        Type t = comp.GetType(); 
        clone.components.Add(Component.CloneComponent<t>()); //This obviously doesn't work
    }
    clone.position = position;
    clone.scale = scale;

    AllGameObjects.Add(clone);
    return clone;
}

我遇到的问题是如何将组件类型用作通用参数。

我目前正在使用要克隆的组件只是更改克隆上的所有者:

public static TComponent CloneComponent<TComponent>(Component toClone) where TComponent : Component, new()
{
    var clone = new TComponent();

    clone.gameObject = toClone.gameObject;

    return clone;
}

组件系统很简单,所有组件都继承自Component类。

示例:

&#13;
&#13;
class PlayerController : Component
{
    public float jumpForce = 5;
    public float walkSpeed = 2;

    RigidBody rb;
    Collider col;

    public override void Start()
    {
        base.Start();

        rb = gameObject.GetComponent<RigidBody>();
        col = gameObject.GetComponent<Collider>();
    }

    bool canJump { get { return jumps > 0; } }
    int jumps = 1;
    int maxJumps = 1;
    public override void Update(GameTime gameTime)
    {
        rb.velocity = new Vector2(Input.GetAxisInputs(Keyboard.GetState(), "Horizontal") * walkSpeed, rb.velocity.Y);
        if (Input.GetKeyOnDown(Keyboard.GetState(), Keys.Space) && canJump)
        {
            rb.velocity = new Vector2(rb.velocity.X, -jumpForce);
            jumps--;
        }

        if (!col.PlaceIsFree(new Vector2(0, 1)))
            jumps = maxJumps;
            
        base.Update(gameTime);
    }
}
&#13;
&#13;
&#13;

(无法获取正确格式化的代码示例,因此我只使用了css片段://)

我不是要求克隆自己的任何事情,只是简单地说明如何获得正确的泛型参数,或者是否有另一种方法来实现它。

1 个答案:

答案 0 :(得分:1)

您应该更改CloneComponent功能的签名:

public static TComponent CloneComponent<TComponent>(TComponent toClone) where TComponent : Component, new()

然后你应该调用这个函数,如:

foreach (var comp in obj.components) //Clone all the components
{
    clone.components.Add(Component.CloneComponent(comp));
}

您还可以使用语法糖来简化调用代码:

public static TComponent Clone<TComponent>(this TComponent toClone) where TComponent : Component, new()
{
    if (toClone == null)
    {
        throw new ArgumentNullException(nameof(toClone));
    }

    var clone = new TComponent();

    clone.gameObject = toClone.gameObject;

    return clone;
}

循环将是:

foreach (var comp in obj.components) //Clone all the components
{
    clone.components.Add(comp.Clone());
}