此代码是否在对象创建后立即通过访问器设置值
var dlg = new Microsoft.Win32.OpenFileDialog
{
Title = "Select configuration",
DefaultExt = ".xml",
Filter = "XML-file (.xml)|*.xml",
CheckFileExists = true
};
我从 这篇 帖子中得到了上述内容。是花括号内的部分,通过访问器赋值。似乎没有构造函数,这是否意味着调用默认构造函数,然后分配属性值。
var dlg = new Microsoft.Win32.OpenFileDialog
{
Title = "Select configuration",
DefaultExt = ".xml",
Filter = "XML-file (.xml)|*.xml",
CheckFileExists = true
};
I got the above piece of got from this post. Is the part inside the curly braces assigning values via Accessors. There appears to be no constructors, so does it imply the default one is called and then Property values assigned.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您所显示的内容称为对象初始值设定项< /a>,C# 3.0 中引入的语法功能。
它与以下代码类似,该代码在第一行中创建一个对象,然后在后续行中单独设置其属性:
但是,它不完全相同上面的代码。当您使用对象初始值设定项时,编译器将创建一个临时变量,设置该临时变量中包含的对象的属性,然后将该临时变量分配给您声明的实际变量。最终结果是对象实例的创建是原子的。更详细的信息可在 这个问题,以及这篇博文。
在实践中,您可以想象完全展开时生成的代码看起来像这样:
至于您关于调用哪个构造函数的问题,是的,在这两种情况下它都是默认构造函数。第一行是对构造函数的调用,当它显示
new
时。您可以看出它是默认构造函数,因为没有传入任何参数。What you've shown is called an object initializer, a syntactical feature introduced in C# 3.0.
It is similar to the following code, which creates an object in the first line, and then sets its properties individually in the subsequent lines:
However, it is not identical to the above code. When you use an object initializer, the compiler will create a temporary variable, set the properties on the object contained in that temporary variable, and then assign that temporary variable to the real variable that you declared. The net result is that the creation of the object instance is atomic. More detailed information is available in the answers to this question, and in this blog post.
In practice, you can imagine the resulting code looking something like this when fully expanded:
As for your question about which constructor is called, yes, it is the default constructor in both cases. The first line is a call to the constructor, when it says
new
. You can tell it's the default constructor because no parameters are passed in.是的,它与以下内容相同:
它完全按照您的猜测进行操作 - 调用构造函数,然后使用公共属性设置器。
Yes it is identical to:
It does exactly what you guessed - call the constructor, then use the public property settors.
是的,它意味着使用默认构造函数创建相同的 ie,并使用访问器来分配值,其 .net3.5 或以上语法支持对象初始化
Yes, it implies the same i-e created with default constructor and used accessors to assign the value, its the .net3.5 or above syntax to support object initialization
是的,这就是语法糖。编译器将为此生成以下代码:
Yes, this is syntactic sugar. The compiler will generate the following code for this: