为什么我可以将集合初始化器与来自另一个类的私有集一起使用? [英] Why can I use a collection initializer with private set access from another class?

查看:65
本文介绍了为什么我可以将集合初始化器与来自另一个类的私有集一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

public sealed class Order
{
    public Order()
    {
        Items = new List<OrderItem>();
    }

    public List<OrderItem> Items { get; private set; }
}

public sealed class OrderItem
{
}

,这是另一个类中的 Order 初始化。

and here's Order initialization in another class.

var order = new Order
{
    Items =
    {
        new OrderItem(),
        new OrderItem()
    }
};

您能解释一下它为什么起作用吗?如您所见, Order 具有 private set 属性,所以我认为不可能设置其值。

Could you explain why it works? As you see the Order has private set property, so I thought it would be impossible to set its value.

推荐答案

简短答案:



通过集合初始化程序,它调用 Add 添加项

根据C#3.0规范化,对象实现 IEnumerable 并具有适当的 Add 方法可以通过 Add 方法进行初始化。

Accodingly C# 3.0 cpesification, object which implement IEnumerable and has appropiate Add method can be initialised thru the Add method.

Items 具有 public get 访问器和 Items List< T> ,它实现了 IEnumerable 并具有 Add 。编译器如何看待您的代码

Items has public get accessor and Items it's a List<T> which implements IEnumerable and has Add. Here's how the compiler sees your code

var order = new Order();
order.Items.Add(new OrderItem());
order.Items.Add(new OrderItem());

请注意,编译器不会使用 List的信息实现了 IEnumerable ,这是证明,不会抛出异常

Please note, the compiler doesn't use info that the List implements IEnumerable, here's the proof, no exception will be thrown

public sealed class Order
{
    public Order()
    {
        Items = new MyCollection();
    }

    public MyCollection Items { get; private set; }
}

public sealed class OrderItem
{
}

public class MyCollection : IEnumerable
{
    private readonly List<OrderItem> _items = new List<OrderItem>();

    public void Add(OrderItem item)
    {
        _items.Add(item);
    }

    public IEnumerator GetEnumerator()
    {
        throw new NotImplementedException();
    }
}

来自 C#语言规范


应用了集合初始值设定项的集合对象
必须是实现 System的类型.Collections.IEnumerable
a发生编译时错误。对于顺序中的每个指定元素,
集合初始值设定项以
元素初始值设定项的表达式列表作为参数列表来调用目标对象上的Add方法,
每次调用均应用正常的重载解析。因此,
集合对象必须为每个
元素初始值设定项包含适用的 Add 方法。

这篇关于为什么我可以将集合初始化器与来自另一个类的私有集一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆