Cast/Convert IEnumerable to IEnumerable?

前端 未结 6 2076
我在风中等你
我在风中等你 2021-01-04 08:48

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 wo

6条回答
  •  渐次进展
    2021-01-04 09:25

    You can't just cast two unrelated type into each other. You could make it possible to convert PersonWithAge to Person by letting PersonWithAge inherit from Person. Since PersonWithAge is obviously a special case of a Person, this makes plenty of sense:

    class Person
    {
            public int Id { get; set; }
            public string Name { get; set; }
    }
    
    class PersonWithAge : Person
    {
            // Id and Name are inherited from Person
    
            public int Age { get; set; }
    }
    

    Now if you have an IEnumerable named personsWithAge, then personsWithAge.Cast() will work.

    In VS 2010 you will even be able to skip the cast altogether and do (IEnumerable)personsWithAge, since IEnumerable is covariant in .NET 4.

提交回复
热议问题