【发布时间】:2009-11-21 16:45:16
【问题描述】:
以下内容符合但在运行时抛出异常。我要做的是将一个 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<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 将始终包含与 Person 相同的属性以及更多属性。
编辑 2 对不起,伙计们,但我应该更清楚一点,比如我在一个包含相同列的数据库中有两个 db 视图,但视图 2 包含 1 个额外字段。我的模型视图实体是由模仿数据库视图的工具生成的。我有一个从类实体之一继承的 MVC 部分视图,但我有不止一种方法来获取数据...
不确定这是否有帮助,但这意味着我不能让 personWithAge 从 person 继承。
【问题讨论】:
标签: c# ienumerable casting