Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

c# - Initializer syntax

I like the C# 3 initializer syntax and use it a lot, but today while looking in Reflector, the following came up:

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

At first I thought it was a mistake, but it does compile! Guess I am still learning new stuff all the time. :)

From what I can tell, it sets the MaxArrayLength property of the ReaderQuotas property of the WSHttpBinding.

Does this syntax create a new ReaderQuotas object and then set the property, or does it assume the property to be initialized already? Is this the general way one would use to initialize 'child' properties?

I do find the syntax a bit confusing...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...