Safely convert List
When working with C# collections, you may encounter situations where you need to convert a list of derived class objects into a list of base interface objects. Although this conversion seems simple, casting between different types can cause potential problems.
Direct casting from one type to another (for example, from List
To safely convert between these two types, we need to create a new list of target types. This can be achieved by iterating the original list and manually adding each element to the new list. For example:
<code class="language-csharp">List<Client> clients = new List<Client>(); List<IDic> dics = new List<IDic>(); // 遍历 Client 列表 foreach (Client client in clients) { // 创建一个新的 IDic 对象并设置其属性 IDic dic = new Dic { Id = client.Id, Name = client.Name }; // 将新的 IDic 对象添加到 dics 列表 dics.Add(dic); }</code>
Additional options in .NET 4 and C# 4
In .NET 4 and C# 4, you can take advantage of the concept of covariance to simplify the conversion of an IEnumerable
<code class="language-csharp">// 使用协变将 IEnumerable<Apple> 转换为 IEnumerable<IFruit> List<IFruit> fruit = apples.AsEnumerable<IFruit>().ToList();</code>
However, it should be noted that covariance only applies to read-only collections. If you modify the original list after creating the IEnumerable
The above is the detailed content of How to Safely Convert a List to a List in C#?. For more information, please follow other related articles on the PHP Chinese website!