演员/转换IEnumerable的< T>到了IEnumerable< U> ;? [英] Cast/Convert IEnumerable<T> to IEnumerable<U>?
问题描述
以下符合规定,但在运行时会抛出异常。我所试图做的是投类PersonWithAge一类人的。我如何做到这一点,什么是身边的工作?
The following complies but at run time throws an exception. What I am trying to do is to cast a class PersonWithAge to a class of Person. How do I do this and what is the work around?
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<PersonWithAge> pwa = new List<PersonWithAge>
{
new PersonWithAge {Id = 1, Name = "name1", Age = 23},
new PersonWithAge {Id = 2, Name = "name2", Age = 32}
};
IEnumerable<Person> p = pwa.Cast<Person>();
foreach (var i in p)
{
Console.WriteLine(i.Name);
}
}
}
编辑:顺便说一句PersonWithAge总是包含相同的属性,另加一对夫妇更。
By the way PersonWithAge will always contain the same properties as Person plus a couple more.
编辑2 对不起球员,但我应该有使这个更清楚一点,说我有一个包含相同的列,但视图2包含1额外字段数据库2分贝意见。我的模型视图实体是由模仿数据库视图工具生成的。我有一个从实体类的一个继承了MVC的部分观点,但我必须抓住的数据不止一种方法...
EDIT 2 Sorry guys but I should have made this a bit clearer, say I have two db views in a database that contains the same columns but view 2 contains 1 extra field. My model view entities are generated by a tool that mimics the database views. I have a MVC partial view that inherits from one of the class entities but I have more than one way to grab data...
不知道这是否帮助,但它意味着我不能让personWithAge由人继承。
Not sure if this helps but it means that I cant make personWithAge inherit from person.
推荐答案
您可以不投,因为它们是不同的类型。你有两个选择:
You can't cast because they are different types. You have two choices:
1)改变类,这样PersonWithAge从人继承
1) Change the class so that PersonWithAge inherits from person.
class PersonWithAge : Person
{
public int Age { get; set; }
}
2)创建新的对象:
2) Create new objects:
IEnumerable<Person> p = pwa.Select(p => new Person { Id = p.Id, Name = p.Name });
这篇关于演员/转换IEnumerable的< T>到了IEnumerable< U> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!