且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从C#中的arralist中检索数据?

更新时间:2023-02-23 08:40:20

首先,停止返回对象 - 返回实际的类,它更有用:

First off, stop returning Objects - return the actual class instead, it's a lot more useful:
public Employee Add()
{
    Employee employeeDetail = new Employee();
    Console.Write("Employee Id:");
    employeeDetail.Id = int.Parse(Console.ReadLine());

    Console.Write("Employee Name:");
    employeeDetail.Name = Console.ReadLine();
    Console.Write("Employee Address:");
    employeeDetail.Address = Console.ReadLine();
    return employeeDetail;
}



但是在真正的应用程序中,你也不应该这样做。您不需要添加方法 - 您应该使用构造函数:


But in a "real" application, you shouldn't do that either. You don't want an "Add" method - you should use a constructor:

public Employee(int id, string name, string address)
    {
    Console.Write("Employee Id:");
    Id = id;
    Name = name;
    Address address;
    }



然后让您的控制台在Main方法中工作并使用结果构建一个新员工:


Then do your Console work in the Main method and use the results to construct a new Employee:

Console.Write("Employee Id:");
int id = int.Parse(Console.ReadLine());
Console.Write("Employee Name:");
string name = Console.ReadLine();
Console.Write("Employee Address:");
string address = Console.ReadLine();
Employee employeeDetail = new Employee(id, name, address);
arrayList.Add(employeeDetail);

这样,您的Employee类可以重复使用,因为它不需要知道信息的来源。



然后,当您从ArrayList中获取对象时,将其强制转换为Employee:

That way, your Employee class is reusable, because it doesn't need to know where the info comes from.

Then, when you fetch an object from your ArrayList, cast it to an Employee:

foreach(Object obj in arraylist)
    {
    Employee emp = obj as Employee;
    Console.Write("{0}: {1}, {2}", emp.Id, emp.Name, emp.Address);
    }



但是...我不会使用ArrayList - 它们非常过时,并且很长时间被Generic集合所取代以前 - 看看使用List< Employee>相反。


But...I wouldn't use an ArrayList - they are very very out of date, and were supplanted by Generic collections a very long time ago - look at using a List<Employee> instead.


您正在尝试编写没有适当ToString()覆盖的对象。有几种方法可以解决这个问题。



修复开关声明:



You're trying to write the object that doesn't have an appropriate ToString() override. There are a few ways you can fix this.

Fix the switch statement:

case 4:
    foreach(Employee obj in arraylist)
    {
        Console.Write(string.Format("{0} {1} {2}",obj.Id, obj.Name, obj.Address));
    }





或者将一个ToString()方法添加到Employee类并保留你已经拥有的switch语句:





Or add a ToString() method to the Employee class and leave the switch statement as you already have it:

public override string ToString()
{
    return string.Format("{0} {1} {2}", this.Id, this.Name, this.Address);
}