[英]C#: I am trying to write a method to create a new instance of a class, with a certain ID input as a parameter in the method
I have created a text adventure thing which loads up a certain type of world file and allows you to play through it, however I am now trying to build a program that allows somebody to actually build one of these worlds. 我创建了一个文本冒险游戏,它可以加载某种类型的世界文件并允许您播放该文件,但是我现在正在尝试构建一个程序,该程序可以使某人实际构建这些世界之一。 I need to be able to add rooms to this world through this AddRoom() method.
我需要能够通过此AddRoom()方法向这个世界添加房间。
public void AddRoom(String id, String name, String description)
{
Room id = new Room(name, description);
}
AddRoom("kitchen1", "Old Kitchen", "A dark, cold, old kitchen");
This should create: 这应该创建:
Room kitchen1;
But of course I can't have the ID of a room being a string, how would I go about changing the AddRoom method so that I was able to determine the name of the room in the parameters. 但是我当然不能将房间的ID设为字符串,我将如何更改AddRoom方法,以便能够在参数中确定房间的名称。
You can use a dictionnary for this. 您可以为此使用字典。 Here's an example:
这是一个例子:
Dictionary<string, Room> rooms = new Dictionary<string, Room>();
this will create a Dictionary where the key is the Room ID (ex: "kitchen1") and the value is the Room
object and in your AddRoom
method you can use it like this: 这将创建一个Dictionary,其中的键是Room ID(例如:“ kitchen1”),值是
Room
对象,在您的AddRoom
方法中,您可以像这样使用它:
public void AddRoom(String id, String name, String description)
{
// Note that the rooms variable must be accessible inside your method
rooms.Add(id, new Room(name, description));
}
and then later your access the room using its id like this: 然后,您可以使用其ID如下访问房间:
rooms["kitchen1"].Name // Or whatever variable the name is stored in
rooms["kitchen1"].Description // Or whatever variable the Description is stored in
public struct Room
{
public String Name;
public String Desc;
}
Dictionary<string, Room> World = new Dictionary<string, Room>();
public void AddRoom(String id, String name, String description)
{
Room room = new Room() { Name = name, Desc = description };
World.Add(id, room);
}
AddRoom("kitchen1", "Old Kitchen", "A dark, cold, old kitchen");
Now to Fetch detail of kitchen1 from world 现在要从世界获取kitchen1的详细信息
Room kitchen = World["kitchen1"];
kitchen.Name //will give name
kitchen.Desc //will give Description of kitchen
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.