Cast/Convert IEnumerable to IEnumerable?

前端 未结 6 2069
我在风中等你
我在风中等你 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 keep the IEnumerable and don't convert it to IEnumerable. Just add an implicit conversion to convert an object of PersonWithAge to Person when you need.

    class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public static implicit operator Person(PersonWithAge p)
        {
            return new Person() { Id = p.Id, Name = p.Name };
        }
    }
    

    List pwa = new List
    Person p = pwa[0];
    

提交回复
热议问题