有没有办法减少共享通用功能的重载方法中出现的重复代码?如果是这样,如何?

Is there a way to reduce the repetitive code present in overloaded methods that share common functionality? If so, how?

在这里,我有两个重载方法,其唯一目的是返回负责渲染四边形的顶点结构列表。

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),
        },
    };
}

如您所见,在为剩余的顶点属性和每个属性的有效组合添加更多重载方法后,它会变得很长。

internal struct Vertex
{
    public Vector3 Position { get; set; }

    public Color4 Color { get; set; }

    public Vector2 TexCoord { get; set; }

    public int TexUnit { get; set; }
}

我知道可以使用其他方法来减少类似的东西来承载通用功能,但我真的不认为它在这种情况下非常适用,因为我相信它不会提供什么改进和对我来说,它似乎有点乱。

按照目前的速度,这个文件将变得非常大并且导航起来很乏味,我觉得它违反了 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) {
}