c#中具有字符串键的数组的数组

本文关键字:数组 字符串 | 更新日期: 2023-09-27 18:19:25

我是C#的新手,但我有PHP背景。在C#中处理一些基本的东西时,我遇到了一些奇怪的事情。我想在C#中创建一个数组,其中包含另一个数组的字符串键。如果我必须在PHP中这样做,它会看起来像这样:

$workers = array("John" => array("salary" => 1000, "bonus" => 200), 
                 "Michal" => array("salary" => 1500, "bonus" => 0)
           );

在C#中,我发现了一些答案,比如hashtable或dictionary,但这让我更加困惑。

c#中具有字符串键的数组的数组

C#与PHP不同,因为它不松散,所以您需要声明数组(如果您想要字符串键,则为哈希表)可以容纳的内容。这意味着,如果您希望拥有一个数组数组,则需要告诉父数组它包含数组,而不能包含任何其他数组。

这里已经基本回答了这个问题:

如何初始化包含词典列表的词典?

.NET中的数组没有键值对,因此需要使用不同的集合,比如字典。

最接近PHP代码的是字典的字典,但是自定义类的字典更符合C#中处理数据的方式。

类别:

public class Worker {
  public int Salary { get; set; }
  public int Bonus { get; set; }
}

字典:

Dictionary<string, Worker> workers = new Dictionary<string, Worker>();
workers.Add("John", new Worker{ Salary = 1000, Bonus = 200 });
workers.Add("Michal", new Worker{ Salary = 1500, Bonus = 0 });

这允许您按名称查找工作人员,然后访问属性。示例:

string name = "John";
Worker w = workers[name];
int salary = w.Salary;
int bonus = w.Bonus;

为对象Worker:创建一个类

public class Worker
{
    public string Name { get; set; }
    public double Salary { get; set; }
    public int Bonus { get; set; }
    public Worker(string name, double salary, int bonus)
    {
        this.Name = name;
        this.Salary = salary;
        this.Bonus = bonus;
    }
}

然后创建一个工人列表:

List<Worker> workers = new List<Worker>() { 
    new Worker("John", 1000, 200),
    new Worker("Michal", 1500, 0)
};

在c#中可以做的事情如下:

public class Employee
{
    public string Name { get; set; }
    public double Salary { get; set; }
    public int Bonus { get; set; }
    public Employee(string name, double salary, int bonus)
    {
        this.Name = name;
        this.Bonus = bonus;
        this.Salary = salary;
    }
}

并创建字典:

Dictionary<string, Employee> emps = new Dictionary<string, Employee>();
emps.Add("Michal", new Employee("Michal", 1500, 0));
emps.Add("John", new Employee("John", 1000, 200));

或者有时您可能希望为我们的员工使用dynamicanonymous type,而不是强类型(如Employee):

        var John = new { Salary = 1000, Bonus = 200 };
        var Michal = new { Salary = 1500, Bonus = 0 };
        var dict = new Dictionary<string, dynamic>()
        {
            {"John", John},
            {"Michal", Michal},
        };
        Console.WriteLine(dict["John"].Bonus);

输出:200