Home >Backend Development >C++ >How Can I Convert a List to a List in C#?
Inheritance in object -oriented programming allows derivatives to inherit the attributes and methods of its base class. However, sometimes it is not clear why this inheritance cannot be applied to generics like List.
Consider the following example:
In this code, the compiler error occurs because the 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>cannot be implicitly converted into list
. Even if the class C inherits the interface A, the compiler cannot automatically convert the set of the derived class into a collection of its base class.
Convertall method accepts a function as a parameter, and creates a new list by applying the function of the function to the source list. In this example, the function (x = & gt; (a) x) forcibly converts each element of list
into type A.<code class="language-csharp">List<A> listOfA = new List<C>().ConvertAll(x => (A)x);</code>
LINQ's Cast () method allows you to convert one type of list into another list. By converting list to list
and then converting it into list, you can create a collection of base class objects from a collection of the derived class object.<code class="language-csharp">List<A> listOfA = new List<C>().Cast<A>().ToList();</code>
The above is the detailed content of How Can I Convert a List to a List in C#?. For more information, please follow other related articles on the PHP Chinese website!