gpt4 book ai didi

c# - c# 声明列表时如何将命名对象添加到列表中

转载 作者:太空宇宙 更新时间:2023-11-03 19:03:57 24 4
gpt4 key购买 nike

我想知道是否有一种语法可以在其声明中将命名对象添加到列表中,以便最终结果是一个对象列表,我可以通过名称引用它们(无需搜索)。

这是很长的路要走(我知道这是可行的),我使用了一个员工列表来说明我正在尝试做的事情。

List<Employee> Employees = new List<Employee>();

Employee Tom = new Employee(id = 001, Department = "Sales");
Employee Joan = new Employee(id = 002, Department= "HR" );
Employee Fred = new Employee(id = 003, Department= "Accounting");

Employees.Add(Tom);
Employees.Add(Joan);
Employees.Add(Fred);

所以上面的工作,我在一个列表中命名了我可以使用的对象。

也可以在声明列表的时候声明Employees:

List<Employee> employees= new List<Employee>()
{
new Employee() { empID = 001, Name = "Tom", Department= "Sales"},
new Employee() { empID = 004, Name = "Joan", Department= "HR"},
new Employee() { empID = 003, Name = "Fred", Department= "Accounting" },
};

但是,我必须在类中将 Name 创建为字符串,而不是 Employee 对象。

我想知道的是,“有没有办法做到这一点?”

List<Employee> employees= new List<Employee>()
{
new Employee() Tom = { empID = 001, Department= "Sales"},
new Employee() Joan = { empID = 024, Department= "HR"},
new Employee() Fred = { empID = 023, Department= "Accounting" },
};

^^显然,上面的方法行不通,但希望它能说明我正在努力实现的目标。

编辑:感谢@Ann L 和 D Stanley 的回答,我想我需要进一步详细说明我要放置的位置,您的示例在这里有效:

<script runat="server">

Employee Tom = new Employee(001, "Sales");
Employee Joan = new Employee(002, "HR");
Employee Fred = new Employee(003, "Accounting");

public List<Employee> Employees;

protected override void OnLoad(EventArgs e)
{
Employees = new List<Employee>() { Tom, Joan, Fred };

base.OnLoad(e);
}
</script>

然而,为了让我的列表可以公开访问,它违背了我将声明和赋值放在同一个地方的目标,因为下面的代码不起作用

<script runat="server">

Employee Tom = new Employee(001, "Sales");
Employee Joan = new Employee(002, "HR");
Employee Fred = new Employee(003, "Accounting");

public List<Employee> Employees = new List<Employee>() { Tom, Joan, Fred };

protected override void OnLoad(EventArgs e)
{


base.OnLoad(e);
}
</script>

在上面,我收到错误“字段初始值设定项无法引用非静态字段、方法或属性”

最佳答案

你在找字典吗?

Dictionary<String, Employee> employees = new Dictionary<String, Employee>() {
{"Tom", new Employee() { empID = 001, Department= "Sales"}},
{"Joan", new Employee() { empID = 024, Department= "HR"}},
{"Fred", new Employee() { empID = 023, Department= "Accounting"}},
};

...

Employee sample = employees["Joan"];

关于c# - c# 声明列表时如何将命名对象添加到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31430642/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com