以下代码在编译时通过,但在运行时抛出异常。我想做的是将一个类 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: 抱歉各位,我应该让这个问题更清晰一些,假设我在数据库中有两个视图,其包含相同的列,但是第二个视图包含一个额外的字段。我的模型视图实体是由模拟数据库视图的工具生成的。我有一个MVC部分视图从一个类实体继承,但我有多种方法来获取数据...
不确定这是否有帮助,这意味着我无法使personWithAge继承自person。