如何访问列表中对象的属性?
How can I access properties of an object within a list?
编辑:为了澄清问题,我试图通过在列表中存储多个对象(所有对象都需要以不同的位置和方式绘制,并且每个对象都有形状等自定义属性)来简化我的代码。我希望能够出于各种目的从列表中的任何给定对象访问这些属性之一,例如稍后在我的程序中绘制列表中该项目唯一的精灵。
我正在尝试访问特定于我创建的列表中每个单独对象的属性,但似乎无法正确访问。我想我遗漏了一些基本的列表!这是我定义岛屿的 class:
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))
};
在我的游戏的绘制方法中,我希望能够访问特定于该岛的矩形,例如而不是写:
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 做到这一点,但我不确定。
你可以做一些不同的事情:
使用列表
Island theIsland = islands.Find(x => x.IslandName == "ShepherdsLookout");
使用字典会提供更好的性能。
Dictionary<string, Island> islands = new Dictionary<string, Island>();
//加载字典数据
岛theIsland = islands["ShephardsLookout"];
无论哪种方式,您都可以使用:
theIsland.Position
检索值
编辑:为了澄清问题,我试图通过在列表中存储多个对象(所有对象都需要以不同的位置和方式绘制,并且每个对象都有形状等自定义属性)来简化我的代码。我希望能够出于各种目的从列表中的任何给定对象访问这些属性之一,例如稍后在我的程序中绘制列表中该项目唯一的精灵。
我正在尝试访问特定于我创建的列表中每个单独对象的属性,但似乎无法正确访问。我想我遗漏了一些基本的列表!这是我定义岛屿的 class:
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))
};
在我的游戏的绘制方法中,我希望能够访问特定于该岛的矩形,例如而不是写:
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 做到这一点,但我不确定。
你可以做一些不同的事情:
使用列表
Island theIsland = islands.Find(x => x.IslandName == "ShepherdsLookout");
使用字典会提供更好的性能。
Dictionary<string, Island> islands = new Dictionary<string, Island>();
//加载字典数据 岛theIsland = islands["ShephardsLookout"];
无论哪种方式,您都可以使用:
theIsland.Position
检索值