这里,我有两个重载方法,其唯一目的是返回Vertex结构的列表。如您所见,在添加更多重载方法后,它将花费相当长的时间。
public static List<Vertex> Quad(Vector3 position, float size)
{
return new List<Vertex>()
{
new Vertex() { Position = new Vector3(position.X - (size / 2), position.Y - (size / 2), position.Z) },
new Vertex() { Position = new Vector3(position.X + (size / 2), position.Y - (size / 2), position.Z) },
new Vertex() { Position = new Vector3(position.X + (size / 2), position.Y + (size / 2), position.Z) },
new Vertex() { Position = new Vector3(position.X - (size / 2), position.Y + (size / 2), position.Z) },
};
}
public static List<Vertex> Quad(Vector3 position, Color4 color, float size)
{
return new List<Vertex>()
{
new Vertex()
{ // struct containing 3 floating-point values: x, y, z
Position = new Vector3(position.X - (size / 2), position.Y - (size / 2), position.Z),
// struct containing 4 floating-point values: Red, Green, Blue, Alpha
Color = new Color4(color.R, color.G, color.B, color.A),
},
new Vertex()
{
Position = new Vector3(position.X + (size / 2), position.Y - (size / 2), position.Z),
Color = new Color4(color.R, color.G, color.B, color.A),
},
new Vertex()
{
Position = new Vector3(position.X + (size / 2), position.Y + (size / 2), position.Z),
Color = new Color4(color.R, color.G, color.B, color.A),
},
new Vertex()
{
Position = new Vector3(position.X - (size / 2), position.Y + (size / 2), position.Z),
Color = new Color4(color.R, color.G, color.B, color.A),
},
};
}
[我知道可以使用其他方法来实现通用功能来减少类似的事情,但是我真的不认为这种方法在这种情况下非常适用,因为我相信它不会给我带来什么改善,似乎有点混乱。
以目前的速度,此文件将变得很大且导航乏味,我觉得它违反了D.R.Y(请勿重复自己)原则。
是否存在更好,更清洁且重复性更低的方法来实现方法重载?如果是这样,如何?
您可能具有较少参数的方法,例如,使用具有某些默认值的所有参数调用该方法
public static List<Vertex> Quad(Vector3 position, float size)
{
Color4 defaultColor = new Color4(...);
return Quad(position, defaultColor, size);
}
如果具有默认值的参数可以是常量,那么您还可以在方法签名中指定默认值,使其成为可选参数:
public static List<Vertex> Quad(Vector3 position, Color4 color, float size = 1f) {
}