首页 > 解决方案 > 如何访问列表中对象的属性?

问题描述

编辑:为了澄清这个问题,我试图通过在列表中存储多个对象(它们都需要以不同的位置和方式绘制,并且每个都有自定义属性,例如形状)来收紧我的代码。我希望能够出于各种目的从列表中的任何给定对象访问这些属性之一,例如稍后在我的程序中绘制列表中该项目唯一的精灵。

我正在尝试访问特定于我创建的列表中每个单独对象的属性,但似乎无法正确处理。我认为我缺少列表的基本内容!这是我定义岛屿的课程:

class Island
{

    public string IslandName { get; set; }

    public Vector2 Position { get; set; }

    public Rectangle IslandRectangle { get; set; }

    public Island(string name, Vector2 position, Rectangle rectangle)
    {
        name = this.IslandName;
        position = this.Position;
        rectangle = this.IslandRectangle;
    }
}

然后,在我的 Main 方法中,我创建了一个新的岛屿列表(现在只有一个):

List<Island> allIslands = new List<Island>()
    {
        new Island("ShepherdsLookout", new Vector2(200, 200), new Rectangle(200,200, 50, 50))
    };

在我的游戏的 draw 方法中,我希望能够访问特定于该岛的矩形,例如,而不是编写:

spritebatch.draw(sprite, new vector2D(200, 200), new rectangle(200, 200, 50, 50));

我想做这样的伪代码:

spritebatch.draw(sprite, islands.shepherdslookout.position, islands.shepherdslookout.rectangle);

我试过使用 IEnumerable 来做到这一点:

 IEnumerable<Island> ShepherdsLookout = from island in allIslands where island.IslandName == "ShepherdsLookout" select island;

但这似乎也不起作用:/我需要一个foreach循环还是什么?我觉得有一些方法可以用 Linq 做到这一点,但我不确定。

标签: c#monogame

解决方案


你可以做几件不同的事情:

  1. 使用列表

    Island theIsland = islands.Find(x => x.IslandName == "ShepherdsLookout");
    
  2. 使用字典将提供更好的性能。

    Dictionary<string, Island> islands = new Dictionary<string, Island>();
    

    //加载字典数据 Island theIsland = Islands["ShephardsLookout"];

无论哪种方式,你都会使用:

theIsland.Position 

检索值


推荐阅读