C#-对象列表-访问对象的参数

时间:2019-12-06 18:47:13

标签: c# .net winforms

我目前正在尝试创建一个简单的rpg C#游戏,并且在地图创建部分还停留得很早。

我为自己的位置创建了一个班级:

memfib(0)

我还创建了一种方法,该方法可以用我的位置填充列表。在主程序区域之外,我创建了该列表,因此所有内容均可访问该列表:

public class Location
{
    private int ID;
    private string Name;
    public Location(int id, string name)
    {
        ID = id;
        Name = name;
    }
}

但是,我现在陷入了困境,因为我不知道如何访问列表中位置对象的参数,因为我只找到了如何从Internet上的列表中访问字符串,或者答案非常复杂且令人困惑我一点都不明白。我想以某种方式使用静态类,因为我了解到它们在我们不想访问类中的信息时很有用,但我认为我不太了解它们的概念。

tl; dr:我想从列表中删除特定对象的ID /名称,但我不知道如何。

3 个答案:

答案 0 :(得分:2)

更改您的Location类以使用公共属性:

public class Location
{
  public int Id {get;set;}
  public string Name {get;set;}
}

您的CreateMap将如下所示:

List<Location> map = CreateMap();

public List<Location> CreateMap()
{
  return new List<Location> {
    new Location {Id=1, Name="START"},
    new Location {Id=2, Name="FOREST"},
    new Location {Id=3, Name="CITY"}
  };
}

然后您可以像这样引用位置:

map.First(m=>m.Id==1).Name

尽管,我会怀疑您会根据ID进行大量查找,并且您的List应该更可能是Dictionary或索引代替ID的简单数组,这将使位置查找更快。在这种情况下,您可以轻松地将其转换成这样的字典:

Dictionary<int,Location> mapDict = CreateMap.ToDictionary(k=>k.Id, v=>v);

然后,您可以通过ID来访问位置,如下所示:

var location = mapDict[1];
var name = location.Name;

答案 1 :(得分:1)

Location成员声明为public,以便您可以使用List.Find(),例如:

Location start = map.Find(l => l.Name == "START");

关于List.Find() here的一些有用信息。

答案 2 :(得分:0)

如果您的Location类属性是公共的,则可以通过如下所示的foreach或for循环来迭代列表:

foreach(var location in map)
{
    var locationId = location.ID;
    var locationName = location.Name;
}

OR

for(var i; i< map.Count; i++)
{
    var locationId = map[i].ID;
    var locationName = map[i].Name;
}

如果Location类属性是私有的,则您需要向Location类添加一个公共函数来完成这项工作。但这不是一个优雅的解决方案:

    public class Location
    {
        private int ID;
        private string Name;
        public Location(int id, string name)
        {
            ID = id;
            Name = name;
        }
        public Tuple<int, string> GetById(int id)
        {
            if (id == this.ID)
            {
                return new Tuple<int, string>(this.ID, this.Name);
            }
            else
            {
                return new Tuple<int, string>(-1, "Not Found");
            }
        }
    }

,然后在外部您可以通过以下方式访问它:

        var map = new List<Location>();
        map.Add(new Location(10, "A"));
        map.Add(new Location(20, "B"));
        map.Add(new Location(30, "C"));
        var bFound = false;
        Tuple<int, string> locationTuple;
        foreach (var location in map)
        {
            var byId = location.GetById(20);
            if (byId.Item1 > -1)
            {
                locationTuple = new Tuple<int, string>(byId.Item1, byId.Item2);
                break;
            }
        }