以下符合但在运行时抛出异常。我想要做的是将 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 相同的属性以及更多属性。
EDIT 2 对不起大家,但我应该更清楚一点,假设我在数据库中有两个数据库 View ,它们包含相同的列,但 View 2 包含 1 个额外的字段。我的模型 View 实体是由模拟数据库 View 的工具生成的。我有一个继承自其中一个类实体的 MVC 局部 View ,但我有不止一种获取数据的方法...
不确定这是否有帮助,但这意味着我不能让 personWithAge 从 person 继承。
最佳答案
你不能转换,因为它们是不同的类型。您有两个选择:
1) 更改类,使 PersonWithAge 继承自 person。
class PersonWithAge : Person
{
public int Age { get; set; }
}
2) 创建新对象:
IEnumerable<Person> p = pwa.Select(p => new Person { Id = p.Id, Name = p.Name });
关于c# - 将 IEnumerable<T> 转换/转换为 IEnumerable<U>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1775984/