初始化对象时调用方法

时间:2016-11-18 12:21:33

标签: c# methods initialization

我正在寻找一种清理代码的方法。我有以下

  var sprite1 = new Sprite(_content.Load<Texture2D>("Content/Block.png"));
  sprite1.Position = new Vector2f(100, 100);
  sprite1.SetInput(Key.A, Key.D, Key.W, Key.S);

  var sprite2 = new Sprite(_content.Load<Texture2D>("Content/Block.png"));
  sprite2.Position = new Vector2f(200, 100);
  sprite2.SetInput(Key.Left, Key.Right, Key.Up, Key.Down);

  _sprites = new List<Sprite>()
  {
    sprite1,
    sprite2,
  };

我想在将其添加到列表时初始化“Sprite”。但我遇到的问题是“SetInput”方法。该方法是可选的。

我知道这在语法上不正确,但下面是我正在讨论的事情

  _sprites = new List<Sprite>()
  {
    new Sprite(_content.Load<Texture2D>("Content/Block.png")) { Position = new Vector2f(100, 100), SetInput(Key.A, Key.D, Key.W, Key.S) },
  };

正如您所看到的,我试图以类似于设置属性的方式调用方法。

以下是我想要解决的方法

  1. 键的可选参数构造函数

    public Sprite(Texture2D texture, Key? left, Key? right, Key? up, Key? down)
    
  2. 带键

    的第二个构造函数
    public Sprite(Texture2D texture, Key left, Key right, Key up Key down)
    
  3. 在初始化时分配的“Sprite”类中创建委托,然后遍历所有_sprites,调用方法

  4. 我在开始时提供的代码很好,我只是想知道是否有更好的方式?

    感谢。

2 个答案:

答案 0 :(得分:1)

你也可以使用所谓的&#34;流利的&#34;接口:

public class Sprite {
     public Sprite SetPosition(Vector2f vector) {
         // set
         return this;
     }

     public Sprite SetInput(Key left, Key right, Key up Key down) {
         // set
         return this;
     }
}

可以像这样使用

 _sprites = new List<Sprite>()
  {
      new Sprite(_content.Load<Texture2D>("Content/Block.png"))
          .SetPosition(new Vector2f(100, 100))
          .SetInput(Key.A, Key.D, Key.W, Key.S)
  };

是否&#34;更好&#34;这是一个品味问题,但它绝对是一种选择。

答案 1 :(得分:1)

如何创建Input类来清理它?

.Grid.Columns

然后你会得到你想要的东西

internal class Sprite
{
    public Input Input { get; set; }
    ... 
}

internal class Input
{
    public Key Left { get; private set; }
    public Key Right { get; private set; }
    public Key Up { get; private set; }
    public Key Down { get; private set; }

    public Input(Key left, Key right, Key up, Key down)
    {
        Left = left;
        Right = right;
        Up = up;
        Down = down;
    }
}
相关问题