将IEnumerable 转换为IEnumerable ?

以下符合但在运行时抛出exception。 我想要做的是将类PersonWithAge强制转换为Person类。 我该怎么做以及解决方法是什么?

class Person { public int Id { get; set; } public string Name { get; set; } } class PersonWithAge { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } } class Program { static void Main(string[] args) { IEnumerable pwa = new List { new PersonWithAge {Id = 1, Name = "name1", Age = 23}, new PersonWithAge {Id = 2, Name = "name2", Age = 32} }; IEnumerable p = pwa.Cast(); foreach (var i in p) { Console.WriteLine(i.Name); } } } 

编辑:顺便说一句,PersonWithAge将始终包含与Person相同的属性以及更多。

编辑2对不起家伙,但我应该让这更清楚一点,说我在包含相同列的数据库中有两个数据库视图,但视图2包含1个额外字段。 我的模型视图实体由模仿数据库视图的工具生成。 我有一个MVC局部视图,它inheritance自一个类实体,但我有多种方法来获取数据…

不确定这是否有帮助,但这意味着我不能让人inheritance人。

你不能投,因为他们是不同的类型。 你有两个选择:

1)更改类,以便PersonWithAgeinheritance自person。

 class PersonWithAge : Person { public int Age { get; set; } } 

2)创建新对象:

 IEnumerable p = pwa.Select(p => new Person { Id = p.Id, Name = p.Name }); 

使用Select而不是Cast来指示如何执行从一种类型到另一种类型的转换:

 IEnumerable p = pwa.Select(x => new Person { Id = x.Id, Name = x.Name }); 

此外,由于PersonWithAge将始终包含与Person相同的属性以及更多的属性,因此最好将其从Personinheritance。

你不能只是将两个不相关的类型相互转换。 您可以通过让PersonWithAgeinheritancePerson来将PersonWithAge转换为Person。 因为PersonWithAge显然是一个Person的特例,所以这很有道理:

 class Person { public int Id { get; set; } public string Name { get; set; } } class PersonWithAge : Person { // Id and Name are inherited from Person public int Age { get; set; } } 

现在,如果你有一个名为personsWithAgeIEnumerable ,那么personsWithAge.Cast()就可以了。

在VS 2010中,您甚至可以完全跳过(IEnumerable)personsWithAge并执行(IEnumerable)personsWithAge ,因为IEnumerable在.NET 4中是协变的。

使PersonWithAgeinheritance自Person。

像这样:

 class PersonWithAge : Person { public int Age { get; set; } } 

您可能希望将代码修改为:

 class Person { public int Id { get; set; } public string Name { get; set; } } class PersonWithAge : Person { public int Age { get; set; } } 

您可以保留IEnumerable ,不要将其转换为IEnumerable 。 只需添加一个隐式转换,即可在需要时将PersonWithAge的对象转换为Person

 class Person { public int Id { get; set; } public string Name { get; set; } public static implicit operator Person(PersonWithAge p) { return new Person() { Id = p.Id, Name = p.Name }; } } 

 List pwa = new List Person p = pwa[0];