Home > Backend Development > C++ > How to Safely Convert a List to a List in C#?

How to Safely Convert a List to a List in C#?

Barbara Streisand
Release: 2025-01-17 00:46:09
Original
191 people have browsed it

How to Safely Convert a List to a List in C#?

Safely convert List in C# to 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 List) is not possible in C# because it would result in unsafe operations. Attempting such a cast may result in unusual or unexpected behavior.

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>
Copy after login

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 to an IEnumerable. This is useful when working with read-only collections:

<code class="language-csharp">// 使用协变将 IEnumerable<Apple> 转换为 IEnumerable<IFruit>
List<IFruit> fruit = apples.AsEnumerable<IFruit>().ToList();</code>
Copy after login

However, it should be noted that covariance only applies to read-only collections. If you modify the original list after creating the IEnumerable view, the changes are not reflected in the derived view.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template