zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    微信小程序@bindgetuserinfo @bindgetphonenumber
    报错总结
    前端面试题
    关于vue ssr next服务端渲染
    【012】JavaSE面试题(十二):多线程(2)
    【011】JavaSE面试题(十一):多线程(1)
    [010]
    [009]
    [008]
    添加Lombok插件后调用Setter或Getter方法IDEA编译错误
  • 原文地址:https://www.cnblogs.com/0banana0/p/2484692.html
Copyright © 2011-2022 走看看