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
};
我从这篇文章中得到了上面的部分。是花括号内的部分,通过访问器分配值。似乎没有构造函数,因此是否暗示调用默认构造函数,然后分配属性值。
您所展示的称为对象初始值设定项,这是 C# 3.0 中引入的一种语法特性。
它类似于以下代码,在第一行创建一个对象,然后在后续行中单独设置其属性:
var dlg = new Microsoft.Win32.OpenFileDialog();
dlg.Title = "Select configuration";
dlg.DefaultExt = ".xml";
dlg.Filter = "XML-file (.xml)|*.xml";
dlg.CheckFileExists = true;
但是,它与上面的代码不同。当您使用对象初始化器时,编译器将创建一个临时变量,设置该临时变量中包含的对象的属性,然后将该临时变量分配给您声明的真实变量。最终结果是对象实例的创建是原子的。此问题的答案和此博客文章中提供了更多详细信息。
在实践中,您可以想象得到的代码在完全展开后看起来像这样:
var temporaryDlg = new Microsoft.Win32.OpenFileDialog();
temporaryDlg.Title = "Select configuration";
temporaryDlg.DefaultExt = ".xml";
temporaryDlg.Filter = "XML-file (.xml)|*.xml";
temporaryDlg.CheckFileExists = true;
var dlg = temporaryDlg;
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.
是的,它等同于:
var dlg = new Microsoft.Win32.OpenFileDialog();
dlg.Title = "Select configuration";
dlg.DefaultExt = ".xml";
dlg.Filter = "XML-file (.xml)|*.xml";
dlg.CheckFileExists = true;
它完全符合您的猜测 - 调用构造函数,然后使用公共属性设置器。
是的,这意味着相同的即使用默认构造函数创建并使用访问器分配值,其.net3.5或更高版本的语法支持对象初始化
是的,这是语法糖。编译器将为此生成以下代码:
var dlg = new Microsoft.Win32.OpenFileDialog();
dlg.Title = "Select configuration";
dlg.DefaultExt = ".xml";
dlg.Filter = "XML-file (.xml)|*.xml";
dlg.CheckFileExists = true;