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

我可以拥有一个不可变的IEnumerable <>吗?

当然可以。在C#中,可以使用System.Collections.Generic.List<T>System.Collections.Generic.HashSet<T>来创建一个不可变的IEnumerable<T>。以下是一个示例:

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

public class ImmutableEnumerable<T> : IEnumerable<T>
{
    private readonly List<T> _list;

    public ImmutableEnumerable(IEnumerable<T> items)
    {
        _list = new List<T>(items);
    }

    public IEnumerator<T> GetEnumerator()
    {
        return _list.GetEnumerator();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

使用这个类,您可以创建一个不可变的IEnumerable<T>,如下所示:

代码语言:csharp
复制
var items = new[] { 1, 2, 3, 4, 5 };
var immutableEnumerable = new ImmutableEnumerable<int>(items);

foreach (var item in immutableEnumerable)
{
    Console.WriteLine(item);
}

这将创建一个不可变的IEnumerable<int>,您可以使用foreach循环遍历其中的元素。请注意,这个实现不会阻止您通过引用直接修改原始列表。如果您需要更严格的不可变性,请考虑使用`System.Collections.ObjectModel.ReadOnlyCollection

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

相关·内容

领券