Nie można przekonwertować z List <DerivedClass> na List <BaseClass>
Próbuję przekazać listęDerivedClass
do funkcji, która pobiera listęBaseClass
, ale dostaję błąd:
cannot convert from
'System.Collections.Generic.List<ConsoleApplication1.DerivedClass>'
to
'System.Collections.Generic.List<ConsoleApplication1.BaseClass>'
Teraz mogę rzucić mojeList<DerivedClass>
do aList<BaseClass>
, ale nie czuję się komfortowo, chyba że rozumiem, dlaczego kompilator na to nie pozwala.
Wyjaśnienia, które znalazłem, po prostu mówiły, że w jakiś sposób naruszają bezpieczeństwo typów, ale tego nie widzę. Czy ktoś może mi pomóc?
Jakie jest ryzyko, że kompilator zezwoli na konwersjęList<DerivedClass>
doList<BaseClass>
?
Oto moja SSCCE:
class Program
{
public static void Main()
{
BaseClass bc = new DerivedClass(); // works fine
List<BaseClass> bcl = new List<DerivedClass>(); // this line has an error
doSomething(new List<DerivedClass>()); // this line has an error
}
public void doSomething(List<BaseClass> bc)
{
// do something with bc
}
}
class BaseClass
{
}
class DerivedClass : BaseClass
{
}