簡體   English   中英

在不使用 inheritance 的情況下重用類似的構造函數

[英]Reuse similar constructors without the use of inheritance

這是 MonoGame 3.8.1 和 .NET 6 的代碼。

public interface IEntity
{
    int Size { get; }
    Vector2 Position { get; }
}
public class Player : IEntity
{
    public int Size { get; } = 32;
    public Vector2 Position { get; private set; }

    public Player(Scene scene)
    {
        var spawnOffset = new Vector2(0, -3);

        Position = new Vector2(
            spawnOffset.X * scene.TileSize + scene.Room.Center.x - Size / 2,
            spawnOffset.Y * scene.TileSize + scene.Room.Center.y - Size / 2);
    }
}
public class Enemy : IEntity
{
    public int Size { get; } = 32;
    public Vector2 Position { get; private set; }

    public Enemy(Scene scene)
    {
        var spawnOffset = new Vector2(0, 0);
    
        Position = new Vector2(
            spawnOffset.X * scene.TileSize + scene.Room.Center.x - Size / 2,
            spawnOffset.Y * scene.TileSize + scene.Room.Center.y - Size / 2);
    }

}

在不使用 inheritance 的情況下,我希望每個實現IEntity的 class 能夠重用Position分配的計算。 兩個構造函數之間的唯一區別是spawnOffset值。

最簡單的方法是什么?

通常 - 我會調用基數 class 構造函數,但在這里我嘗試在沒有基數 class 的情況下執行此操作。

看起來你遵循“更喜歡組合而不是繼承” - 實際上這是一種有效的方法,只需通過將“位置”功能提取到單獨的 class 中來完成它:


class EntityPosition
{
    public Vector2 Position { get; private set; }
    public EntityPosition (Scene scene, Vector2 spawnOffset, int size)
    {
       Position = new Vector2(
        spawnOffset.X * scene.TileSize + scene.Room.Center.x - size / 2,
        spawnOffset.Y * scene.TileSize + scene.Room.Center.y - size / 2);
    }
    // add other shared methods for position updates here as necessary
}

public class Player : IEntity
{
    EntityPosition position;
    public int Size { get; } = 32;
    public Vector2 Position => position.Position;

    public Player(Scene scene)
    {
        var spawnOffset = new Vector2(0, -3);

        position = EntityPosition(scene, spawnOffset, Size);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM