Skip to main content
 首页 » 编程设计

c#之如何在自定义类中创建名称数组

2024年02月06日15mfryf

所以我在 C# 中创建了一个新工具,我创建了一个名为“客户”的类,每个“客户”都有员工子组,这是一个名称数组。如何在我的类中为“客户”设置此属性?我在下面为“员工”提供的内容不正确。我只是把它留在那里作为占位符。 谢谢

public class Customer 
{ 
    public String Number { get; set; } 
    public String Name { get; set; } 
    public String Street { get; set; } 
    public String City { get; set; } 
    public String State { get; set; } 
    public String Zipcode { get; set; } 
    public string[] Employees = { get; set; } 
} 

请您参考如下方法:

您可以使用 List 而不是数组,因为它更易于操作:

public class Customer 
{ 
    public String Number { get; set; } 
    public String Name { get; set; } 
    public String Street { get; set; } 
    public String City { get; set; } 
    public String State { get; set; } 
    public String Zipcode { get; set; } 
    public List<string> Employees { get; set; } 
} 

然后当你实例化它时,你可以这样添加新的雇主:

Customer customer = new Cusomter(); 
customer.Number = "num1"; 
customer.Name = "ABC"; 
//... 
 
List<string> lstEmp = new List<string>(); 
lstEmp.Add("NewEmployee1"); 
lstEmp.Add("NewEmployee2"); 
 
customer.Employees = lstEmp; 

然后像这样阅读:

foreach (string name in customer.Employees) 
{ 
    Console.WriteLine(name); 
}