我有一个包含一个名称和一个整数值的排序列表。我是一个新的C sharp,所以我不知道我做错了什么。
我的代码是
我的代码: /first class
class Tool {
public Tool(string name, int quantity)
{
this.name = name;
this.quantity = quantity;
}
}
/主课
这是一个不同的班级(二班)。
SortedList<Tool> gardeningTools = new SortedList<Tool>(); //error
gardeningTools.Add(new Tool("nameA", 1)); //error
我想在园艺工具里面添加一些工具。上面两行有错误说 "new "不是一个有效的关键词,而且两行都是红色的。我想这完全是一种错误的写法,这样写。谁能告诉我怎么写才是正确的?
排序列表 需要两个通用类型参数,即键的类型和你要存储的项目的类型。在你的例子中,这可能是。
SortedList<string, Tool> gardeningTools = new SortedList<string, Tool>();
假设 Tool
是这样定义的。
class Tool
{
public Tool(string name, int quantity)
{
this.Name = name;
this.Quantity = quantity;
}
public string Name{get;}
public int Quantity{get;}
}
另外, Add
方法需要两个参数,key和value,所以你需要这样的东西。
Tool tool = new Tool("nameA", 1);
gardeningTools.Add(tool.Name, tool);
现在你可以按顺序访问它们 例如:
foreach(var tool in gardeningTools.Values)
{
Console.WriteLine("Name = {0}, Qty = {1}", tool.Name, tool.Quantity);
}