以下符合但在运行时抛出异常。我想要做的是将PersonWithAge类转换为Person类。我如何做到这一点,以及周围的工作是什么?演员/转换IEnumerable <T>到IEnumerable <U>?
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总是包含加相同的属性,人一对夫妇更。
编辑2对不起,但我应该让这个更清楚一点,比如我有一个数据库中有两个数据库视图,包含相同的列,但视图2包含1个额外的字段。我的模型视图实体由模仿数据库视图的工具生成。我有一个MVC的局部视图,从一个类实体继承,但我有不止一种方式来抓取数据...
不知道这是否有帮助,但这意味着我不能让personWithAge继承人。
选择的方式可能是前进的方向,但我希望惩罚,因为这可能不是一种精益方式。 – Rippo 2009-11-21 17:07:52