简体   繁体   English

字典C#与类

[英]Dictionary C# with class

today i have a big problem and a heartache... 今天我有一个大问题和心痛...

I have a problem with Dictionary. 我的字典有问题。 I wan't to receipt retrieve a Name of a "room" (it's the system) with and ID, but i have this structure: 我不希望通过收据检索带有ID和ID的“房间”(即系统)的名称,但是我具有以下结构:

class RoomManager
{
    public readonly Dictionary<uint, Room> _rooms;

    public RoomManager()
    {
        _rooms = new Dictionary<uint, Room>();

        AddRoom(new Room(1, "den.png", "The Den", 1));
        AddRoom(new Room(2, "disco.png", "Disco", 1));
        AddRoom(new Room(3, "brunch.png", "Brunch", 2));
        AddRoom(new Room(4, "disco.png", "Disco 2", 3));
    }

    public Dictionary<uint, Room> GetRooms()
    {
        return _rooms;
    }


    public bool AddRoom(Room room)
    {
        if (_rooms.ContainsKey(room.ID))
        {
            return false;
        }
        _rooms.Add(room.ID, room);
        return true;
    }



}

And the most important: 最重要的是:

class Room
{
    public uint ID;
    public string Codename;
    public string Name;
    public int Category;

    public Room(uint id, string codename, string name, int category)
    {
        ID = id;
        Codename = codename;
        Name = name;
        Category = category;
    }
}

It's a system with Socket, so with the adding of Room, all is display on a webpage and when i click on it, the website send me the ID and me, i want to display in the Console the name of "Room clicked"! 这是一个带有Socket的系统,因此添加Room后,所有内容都会显示在网页上,当我单击它时,网站会向我发送ID和我,我想在控制台中显示“ Room clicked”的名称!

So in conclusion: How do I retrieve with a function the name of it with his ID? 因此得出结论:如何使用函数检索带有其ID的名称?

If I understand your question correctly, this code should work 如果我正确理解您的问题,则此代码应该可以正常工作

public String getRoomName(uint id)
{
  string name;
  return _rooms.TryGetValue(id, out name) ? name : "";
  // Have an empty string to catch exceptions (this part isn't necessary but it could be helpful if you don't know that the room exists)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM