C#Lyrics are transformed into a list of base class
The inheritance mechanism allows us to create new classes based on the existing class, but the same concept is not directly applicable to generic lists. Specifically, we cannot declare a
and assign a list of derived types, even if the derived class inherits the self -based class. Please consider the following example:
List<基类>
<code class="language-csharp">interface A { } class B : A { } class C : B { } class Test { static void Main(string[] args) { A a = new C(); // 正确 List<A> listOfA = new List<C>(); // 编译错误 } }</code>
conversion method
The method of converting to is to iterate the list elements and manually convert them manually. This can be implemented using
Method:
List<派生类>
List<基类>
Here, each of the elements in the iteratory C list convert it to type A and add it to the new Listofa list. ConvertAll
<code class="language-csharp">List<A> listOfA = new List<C>().ConvertAll(x => (A)x);</code>
or, we can use Linq to execute the conversion:
Here, convert each element in the list to type A, and
creates a new list containing the conversion element.The above is the detailed content of How to Convert a List of Derived Classes to a List of Base Classes in C#?. For more information, please follow other related articles on the PHP Chinese website!