gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 09:10:24 25 4
gpt4 key购买 nike

我遇到了以下代码:

var process = new Process
{
StartInfo =
{
Arguments = arguments,
FileName = applicationPath,
UseShellExecute = false,
RedirectStandardOutput = true,
CreateNoWindow = true
}
};

我觉得很困惑:为什么你能够省略 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);
}

最佳答案

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

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

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

或任何其他构造函数

var listener = new System.Diagnostics.ConsoleTraceListener(true)
{
TraceOutputOptions = TraceOptions.Timestamp
};

你应该习惯这种实例化

关于c# - 实例化一个对象,但使用大括号而不是默认构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42997409/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com