Unable to cast object of type 'System.Object[]' to type 'Employee[]'

错误:Unable to cast object of type 'System.Object[]' to type 'Employee[]'

public class Employee 
{ 
  public int id; 
  public string firstName; 
  public string lastName; 
 
  public static ArrayList GetEmployeesArrayList() 
  { 
    ArrayList al = new ArrayList(); 
 
    al.Add(new Employee { id = 1, firstName = "Joe", lastName = "Rattz" }); 
    al.Add(new Employee { id = 2, firstName = "William", lastName = "Gates" }); 
    al.Add(new Employee { id = 3, firstName = "Anders", lastName = "Hejlsberg" }); 
    al.Add(new Employee { id = 4, firstName = "David", lastName = "Lightman" }); 
    al.Add(new Employee { id = 101, firstName = "Kevin", lastName = "Flynn" }); 
    return (al); 
  } 
 
  public static Employee[] GetEmployeesArray() 
  { 
    return ((Employee[])GetEmployeesArrayList().ToArray()); //报错
  } 
} 

解决办法三种:

    1. Let the GetEmployeesArrayList return a generic list: e.g. List<Employee>. The ToArray() method of List<Employee> will return a Employee[] array (when using another generic type, you will automatically use the Enumerable.ToArray() extension method).
    2. Use the Cast<T> extension method, before calling ToArray:
      return GetEmployeesArrayList().Cast<Employee>().ToArray();
    3. Use the ArrayList.ToArray(Type) overload as Tamer Oz showed.

1.直接返回固定的list例如 list<Employee>

2.return GetEmployeesArrayList().Cast<Employee>().ToArray();

3.使用 ArrayList.ToArray(Type)的重载

4.有人补充了一个幽默的回答:

  Burn the book.
A book about Linq that uses ArrayList can not be trusted.

烧书

烧所有linq的书 arraylist是不可信的.....

参考:http://social.msdn.microsoft.com/Forums/en-AU/csharplanguage/thread/895254a0-8bcb-42ba-b0a5-c4718e717e00

原文地址:https://www.cnblogs.com/0banana0/p/2484692.html