在我的程序中,我有以下代码:
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
不包含它们的定义。如何使此方法有效?
答案 0 :(得分:3)
由于Vector2
和Vector3
都没有派生或实现的公共基类或接口,因此您需要创建一个直接采用X
和Y
的方法并创建两个调用此新方法的辅助方法:
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),但仍支持Vector2
和Vector3
。
答案 1 :(得分: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);
答案 2 :(得分:0)
然后我会写两个单独的方法,一个用于Vector2
,另一个用于Vector3
。一般来说,你可以使用generic type constraint,但我认为这在某种程度上太过于人为。
答案 3 :(得分:0)
我不知道Vector2和Vector3是否有一些通用的接口或基类,但你可以像这样在你的泛型方法中添加一个约束:
private void Method<T>(T bla)
where T : BaseInterfaceOrBaseClass
{ ... }