c# - 为什么使用只读IEnumerable <T>

标签 c# ienumerable immutability readonly mutability

为什么要声明IEnumerable<T> readonly

从这个article on async & await中,我们有以下代码。

class OrderHandler
{
    private readonly IEnumerable<Order> _orders;

    public OrderHandler()
    {
        // Set orders.
    }
    public IEnumerable<Order> GetAllOrders()
    {
        return _orders;
    }
}


IEnumerable<T>是不可变的。与readonly关键字有何不同?

最佳答案

此处的readonly关键字适用于字段_orders。这仅表示在对象的生存期内不能为字段分配其他值。例如,这是不可能的:

class OrderHandler
{
    private readonly IEnumerable<Order> _orders;

    public OrderHandler()
    {
        // Set orders.
    }

    void SomeMethod()
    {
        _orders = new Order[0];
    }
}


您将收到此编译器错误:


  不能将readonly字段分配给它(在构造函数或变量初始化程序中除外)


这不会使集合为只读。例如,您仍然可以这样做:

class OrderHandler
{
    public readonly IEnumerable<Order> Orders;

    public OrderHandler()
    {
        Orders = new List<Order>();
    }
}

((List<Order>)OrderHandler.Orders).Add(new Order());


这可能会违反该类的线程安全性。有关不可变集合的信息,请参见Tigran's answer

进一步阅读


readonly (C# Reference)

关于c# - 为什么使用只读IEnumerable <T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17649703/

相关文章:

graph - 在 F# 中制作循环图。是否需要可变性?

c# - 当两者都是引用类型时,字符串与类

javascript - 如何按值从不可变的 js 映射中获取特定对象?

c# - 在 C# 中使用 BeginRead 捕获异常

c# - 具有公共(public)字段的不同类之间的 IEnumerable.Except()

c# - 用 IEnumerable<> 源填充 Dictionary<>

C#:IEnumerable<T> 的循环枚举

c# - 双变量给出意想不到的结果

javascript - 当完整的请求信息出现在浏览器的网络选项卡中时,如何避免多次 POST

c# - 如何使用 C# .net 核心访问 cloudwatch 日志事件