0

在我的程序中,我有以下代码:

 private void SetCorners<T>(T position, int width, int height)
    {
        float halfWidth = width / 2 + position.X;
        float halfHeight = height / 2 + position.Y;

        UpperLeft = new Vector2(-halfWidth, -halfHeight);
        UpperRight = new Vector2(halfWidth, -halfHeight);
        LowerLeft = new Vector2(-halfWidth, halfHeight);
        LowerRight = new Vector2(halfWidth, halfHeight);
    }

其中 T 要么是Vector2要么Vector3来自Microsoft.Xna.Framework。此代码不构建,因为T不包含它们的定义。如何使此方法有效?

4

4 回答 4

3

因为没有共同的基类或接口都Vector2派生Vector3自或实现,所以您将创建一个方法,该方法直接采用XY创建两个调用此新方法的辅助方法:

private void SetCorners(Vector2 position, int width, int height)
{
    SetCorners(position.X, position.Y, width, height);
}

private void SetCorners(Vector3 position, int width, int height)
{
    SetCorners(position.X, position.Y, width, height);
}

private void SetCorners(float x, float y, int width, int height)
{
    float halfWidth = width / 2 + x;
    float halfHeight = height / 2 + y;

    UpperLeft = new Vector2(-halfWidth, -halfHeight);
    UpperRight = new Vector2(halfWidth, -halfHeight);
    LowerLeft = new Vector2(-halfWidth, halfHeight);
    LowerRight = new Vector2(halfWidth, halfHeight);
}

这使您可以不重复自己 ( DRY ),但仍然支持Vector2Vector3

于 2013-02-19T12:31:52.443 回答
1

您还可以为这两个结构创建一个包装类:

private void SetCorners<T>(T position, int width, int height)
    where T : MyVectorWrapper
{
    float halfWidth = width / 2 + position.X;
    float halfHeight = height / 2 + position.Y;

    UpperLeft = new Vector2(-halfWidth, -halfHeight);
    UpperRight = new Vector2(halfWidth, -halfHeight);
    LowerLeft = new Vector2(-halfWidth, halfHeight);
    LowerRight = new Vector2(halfWidth, halfHeight);
}

class MyVectorWrapper
{
    public float X { get; set; }
    public float Y { get; set; }

    public MyVectorWrapper(dynamic vector2)
    {
        X = vector2.X;
        Y = vector2.Y;
    }
}

示例用法:

var v2 = new Vector2(1, 2);
var v3 = new Vector3(v2, 3);
SetCorners<MyVectorWrapper>(new MyVectorWrapper(v2), width, height);
SetCorners<MyVectorWrapper>(new MyVectorWrapper(v3), width, height);
于 2013-02-19T13:09:25.333 回答
0

然后我会编写两个单独的方法,一个 forVector2和一个 for Vector3。一般来说,您可以使用泛型类型约束,但我认为这在这里有点太人为了。

于 2013-02-19T12:32:39.153 回答
0

我不知道 Vector2 和 Vector3 是否有一些共同的接口或基类,但你可以像这样向你的泛型方法添加一个约束:

private void Method<T>(T bla)
  where T : BaseInterfaceOrBaseClass
{ ... }
于 2013-02-19T12:34:16.390 回答