如何在 SortedList 中存储对象

How to store Object in SortedList

我有一个包含名称和整数值的排序列表。我是 c sharp 的新手,所以我不确定我做错了什么。

我的代码:

//第一个class

class Tool {
 public Tool(string name, int quantity)
        {
            this.name = name;
            this.quantity = quantity;
        }
}

//主要class

这是一个不同的class(第二个class)

 SortedList<Tool> gardeningTools = new SortedList<Tool>(); //error


        gardeningTools.Add(new Tool("nameA", 1)); //error 

这里我尝试在园艺工具中添加一些工具。上面两行有错误说 "new" is not a valid keyword 并且这两行都是红色的。我认为这样写是完全错误的。谁能告诉我怎么写才是正确的?

SortedList 需要两个通用类型参数,键的类型和您要存储的项目的类型。在您的情况下,这可能是:

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 方法有两个参数,键和值,所以你需要这样的东西:

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);
}