使用文本指向类的类填充列表

时间:2011-09-20 09:17:46

标签: c# polymorphism

如何减少此_tile分配,以便我可以进行单一分配?

x是一个匿名列表。

x => List {String name, int x, int y}

和一个List _tiles

_tiles.AddRange(from tile in x
where tile.Type.ToLower() == "start".ToLower()
select new Start(this)
{
Position = new Vector2(tile.X, tile.Y),
Texture = _texture2D

});

_tiles.AddRange(from tile in x
where tile.Type.ToLower() == "One".ToLower()
select new OneTouch(this)
{
Position = new Vector2(tile.X, tile.Y),
Texture = _texture2D

});

...

_tiles.AddRange(from tile in x
where tile.Type.ToLower() == "Two".ToLower()
select new ReverseTouch(this)
{
Position = new Vector2(tile.X, tile.Y),
Texture = _texture2D

1 个答案:

答案 0 :(得分:0)

IEnumerable<Tile> tiles = x.Select(tile =>
{
  Tile currentTile = null;

  switch (tile.Type.ToLower())
  {
    case "start":
      currentTile = new Start(this);
      break;

    case "One":
      currentTile = new OneTouch(this);
      break;

    case "Two":
      currentTile = new Start(this)
      break;

    ...

    default:
      // You know what to do...
   }

   currentTile.Position = new Vector2(tile.X, tile.Y),
   currentTile.Texture = _texture2D

   return currentTile;
});

从那里你可以使用tiles.ToList()建立一个列表 或使用_tiles.AddRange(tiles);

填写现有的