实例化一个对象,但使用大括号而不是默认构造函数?

Ric*_*ish 2 .net c#

我遇到过以下代码:

var process = new Process
{
     StartInfo =
     {
          Arguments = arguments,
          FileName = applicationPath,
          UseShellExecute = false,
          RedirectStandardOutput = true,
          CreateNoWindow = true
     }
};
Run Code Online (Sandbox Code Playgroud)

我觉得很困惑:为什么你能够省略 Process 之后的 () ?我假设这只是实例化进程对象,并在其上设置 StartInfo,但我不知道您可以使用这种语法。

MSDN 以传统语法显示了类似的内容:

Process myProcess = new Process();

try
{
    myProcess.StartInfo.UseShellExecute = false;
    myProcess.StartInfo.FileName = "C:\\HelloWorld.exe";
    myProcess.StartInfo.CreateNoWindow = true;
    myProcess.Start();
}
catch (Exception e)
{
    Console.WriteLine(e.Message);
}
Run Code Online (Sandbox Code Playgroud)

She*_*ron 5

此表示法隐式调用默认构造函数,并允许您快捷地初始化实例字段/属性。

您还可以显式调用默认构造函数

var process = new Process()
{
    StartInfo =
    {
        Arguments = arguments,
        FileName = applicationPath,
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};
Run Code Online (Sandbox Code Playgroud)

或任何其他构造函数

var listener = new System.Diagnostics.ConsoleTraceListener(true)
{
    TraceOutputOptions = TraceOptions.Timestamp
};
Run Code Online (Sandbox Code Playgroud)

你应该习惯这种实例化