Cast / Convert IEnumerable< T>到IEnumerable< U> [英] Cast/Convert IEnumerable<T> to IEnumerable<U>?

查看:114
本文介绍了Cast / Convert IEnumerable< T>到IEnumerable< U>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下符合,但在运行时会抛出异常。我想做的是将一个类PersonWithAge类转换为Person。我如何做到这一点,它的工作是什么?

The following complies but at run time throws an exception. What I am trying to do is to cast a class PersonWithAge to a class of Person. How do I do this and what is the work around?

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);
        }
    }
}

/ strong>顺便说一句PersonWithAge总是包含与Person相同的属性加上几个。

By the way PersonWithAge will always contain the same properties as Person plus a couple more.

EDIT 2 使得这更清楚一点,说我有一个数据库中包含相同的列,但视图2包含1个额外字段的两个数据库视图。我的模型视图实体是由模仿数据库视图的工具生成的。我有一个MVC部分视图,继承自一个类实体,但我有多种方式来抓取数据...

EDIT 2 Sorry guys but I should have made this a bit clearer, say I have two db views in a database that contains the same columns but view 2 contains 1 extra field. My model view entities are generated by a tool that mimics the database views. I have a MVC partial view that inherits from one of the class entities but I have more than one way to grab data...

不知道这是否有帮助,但它意味着我不能让personWithAge从人继承。

Not sure if this helps but it means that I cant make personWithAge inherit from person.

推荐答案

你不能投射,因为他们是不同的类型。您有两个选择:

You can't cast because they are different types. You have two choices:

1)更改类,以便PersonWithAge从人继承。

1) Change the class so that PersonWithAge inherits from person.

class PersonWithAge : Person
{
        public int Age { get; set; }
}

2)创建新对象:

IEnumerable<Person> p = pwa.Select(p => new Person { Id = p.Id, Name = p.Name });

这篇关于Cast / Convert IEnumerable&lt; T&gt;到IEnumerable&lt; U&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆