我想知道是否有办法写例如:
Thread th = new Thread(smth);
th.IsBackground = true;
th.Start();
在一行中(也有更多属性)?
new Thread(smth).{IsBackground = true, Start()} ;
答案 0 :(得分:4)
你几乎拥有它,你可以这样做:
var thread = new Thread(smth)
{
IsBackground = true
};
不需要.
。它们被称为对象初始化器,您可以阅读更多相关信息here。
您无法使用方法执行此操作,当然您仍需要在此之外调用Start()
。
答案 1 :(得分:2)
你可以这样写:
new Thread(smth){IsBackground = true}.Start();
答案 2 :(得分:1)
您只能在一行中初始化属性。你必须在另一行调用方法。
Thread th = new Thread(smth){ IsBackground = true;};
th.Start();
答案 3 :(得分:1)
在ObjectInitializer
中分配属性而不是其他任何内容。
您必须在Initializer Block之外调用Start方法。
var th= new Thread(smth)
{
IsBackground = true
};
th.Start();
或
new Thread(smth)
{
IsBackground = true
}.Start();