-1

我有基类 User ant 两个继承的类 - Employee 和 ExtEmployee。

class User { ... }
class Employee : User { ... }
class ExtEmployee : User { ... }

例如两种方法 - GetUsers() 和 GetUsers2()。GetUsers() 返回所有用户。GetUsers2() 具有过滤器并从 currentOrganization 返回用户。

public User[] GetUsers()
{
  Employee[] list1 = GetEmployees();
  ExtEmployee[] list2 = GetExtEmployees(); // empty list

  var list = list1.OfType<User>().Union(list2).ToArray();

  return list;
}

public User[] GetUsers2()
{
  Employee[] list1 = GetEmployees();
  ExtEmployee[] list2 = GetExtEmployees(); // empty list

  var list = list1.OfType<User>().Union(list2).ToArray();

  list = list.Where(u => u.OrganizationId == _currentOrganizationId).ToArray();

  returt list;
}

public void Main()
{
  var employees = GetUsers() as Employee[]; // works fine
  var employees2 = GetUsers2() as Employee[]; // employee2 == null
}

我无法将方法 GetUsers2() 的结果转换为 Employee[] - 我得到空值。为什么?

4

1 回答 1

1

在您的示例中,两条线都应等于null. 您不能将User[]数组转换为Employee[]数组。这些是不同的类型。

但是,您可以使用IEnumerable.Cast<T>()IEnumerable.OfType<T>()方法来执行转换:

//will remove `ExtEmployee` objects.
var employees2 = GetUsers2().OfType<Employee>().ToArray();
//will throw InvalidCastException on ExtEmployee objects unless you define cast operator
var employees2 = GetUsers2().Cast<Employee>().ToArray();
于 2013-10-30T09:11:08.750 回答