初始化程序语法初始化、语法、程序

2023-09-02 10:45:18 作者:Estrus(动情)

我喜欢C#3初始化的语法,使用它了很多,但今天同时寻找在反射器,下面上来:

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. :)

这是我可以告诉,它集的WSHttpBinding 。

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

这是否语法创建一个新的 ReaderQuotas 对象,然后设置该属性,或是否承担被已经初始化属性?这是一款将用于初始化的'孩子'性质的一般方式?

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...

推荐答案

没有,除非你使用不创建新的对象 =新SOMETYPE {...}

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.

您code是的大致的媲美:

Your code is broadly comparable to:

var binding = new WSHttpBinding();
binding.ReaderQuotas.MaxArrayLength = 100000;
binding.MaxReceivedMessageSize = 10485760;
 
精彩推荐