Initializer syntax

前提是你 提交于 2019-11-27 08:34:52

No, that doesn't create new objects unless you use = new SomeType {...}:

var binding = new WSHttpBinding
{
    ReaderQuotas = new XmlDictionaryReaderQuotas { MaxArrayLength = 100000 },
    MaxReceivedMessageSize = 10485760
};

Your example shows the initializer syntax for setting properties of existing sub-objects. There is also a similar syntax for calling "Add" methods on collections.

Your code is broadly comparable to:

var binding = new WSHttpBinding();
binding.ReaderQuotas.MaxArrayLength = 100000;
binding.MaxReceivedMessageSize = 10485760;
Eric Lippert

It is a bit confusing, I agree.

You should read section 7.6.10.2 of the specification; it is all explained there. For example:

A member initializer that specifies an expression after the equals sign is processed in the same way as an assignment to the field or property.

A member initializer that specifies an object initializer after the equals sign is a nested object initializer, i.e. an initialization of an embedded object. Instead of assigning a new value to the field or property, the assignments in the nested object initializer are treated as assignments to members of the field or property. Nested object initializers cannot be applied to properties with a value type, or to read-only fields with a value type.

A member initializer that specifies a collection initializer after the equals sign is an initialization of an embedded collection. Instead of assigning a new collection to the field or property, the elements given in the initializer are added to the collection referenced by the field or property.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!