Answer the question
In order to leave comments, you need to log in
How to make a list of an inherited class from a base class list?
Good afternoon. stumbled on the following problem:
There is a main class:
public class A
{
public string a { get; set; }
//Всего около 100 свойств
}
There is an inherited class:public class B : A
{
public string b { get; set; }
//Всего около 10 дополнительных свойств
}
List<A>
, now there is a need List<A>
to create from List<B>
, however, none of the examples found leads to the desired result:List<A> listA = getListA();
List<B> listB = listA.OfType<B>().ToList();
// Не ругается, но список пустой
List<A> listA = getListA();
List<B> listB = listA.Cast<B>().ToList();
// Выдаёт Exception: Ivalid Cast
Answer the question
In order to leave comments, you need to log in
* Something wrong with the design .*
You can't directly downcastA
objects into objects B
, because A is not B . Because it B
contains some additional state ( b
), which is not in A
and the compiler does not know what it should be in its current form (it was A
constructed differently than B
and how to get a valid B
from A
- only the programmer knows). The runtime ( )
is trying to tell you about this .
As for methods that don't result in what you want: - filters by type and legitimately returns an empty list (you have a list , there really isn't )Invalid Cast
Enumerable.Cast<T>()
- consistently makes casts, which is impossible.
We can try to copy the objects into a new list:
But this will work only if we can get the A
necessary data from to construct the object B
. It is important to understand that these will be OTHER objects. If A is inherently non-copyable, then this trick will fail.
Create a constructor in class B that takes class A and initializes its fields with values from A. Thenvar listB = listA.Select(a=>new B(a)).ToList();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question