c# - 将 IEnumerable<T> 转换/转换为 IEnumerable<U>?

标签 c# ienumerable casting

以下符合但在运行时抛出异常。我想要做的是将 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/

相关文章:

java - 我应该如何编写 .i 文件以用 Java 或 C# 包装回调

.net - 是否可以隐含泛型 List<T> 的数据类型?

c# IEnumerable 双重迭代

c++ - 转换一个由迭代器指向的对象

c# - C# 中巧妙的 5x5 字母网格

c# - 比较两个日期时间 - 没有小时和秒

c# - 从 web.config 按名称读取 WCF 服务终结点地址

c# - Where() 的 IEnumerable lambda 表达式

将 int 转换为 double 将返回 #INF00

c++ 字符串到 uint8_t