首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何使IEnumerable <T>只读?

要使IEnumerable<T>只读,可以使用ReadOnlyCollection<T>类型。ReadOnlyCollection<T>是一个包装类,它将IEnumerable<T>转换为只读集合,以防止修改。以下是如何使用ReadOnlyCollection<T>的示例:

代码语言:csharp
复制
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

public class Program
{
    public static void Main()
    {
        // 创建一个普通的 List<T>
        List<int> list = new List<int> { 1, 2, 3, 4, 5 };

        // 将 List<T> 转换为只读的 ReadOnlyCollection<T>
        ReadOnlyCollection<int> readOnlyCollection = new ReadOnlyCollection<int>(list);

        // 尝试修改只读集合将引发 NotSupportedException
        try
        {
            readOnlyCollection[0] = 99;
        }
        catch (NotSupportedException ex)
        {
            Console.WriteLine("尝试修改只读集合将引发 NotSupportedException: " + ex.Message);
        }

        // 输出只读集合的内容
        foreach (int item in readOnlyCollection)
        {
            Console.WriteLine(item);
        }
    }
}

在这个示例中,我们首先创建了一个普通的List<int>,然后将其转换为ReadOnlyCollection<int>。尝试修改只读集合将引发NotSupportedException。最后,我们遍历并输出只读集合的内容。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券