如何在using语句中使用对象初始值设定项?

时间:2012-10-16 19:51:48

标签: c# refactoring using using-statement

有没有办法重构这段代码,不必使用临时变量,仍然使用与对象初始化器相关的语法糖?

FrmSomeForm someTempForm = new FrmSomeForm()
{
    SomePropA = "A",
    SomePropB = "B",
    SomePropC = "C"
};
using (FrmSomeForm someForm = someTempForm)
{
    someForm.ShowDialog();
}

5 个答案:

答案 0 :(得分:5)

using (FrmSomeForm someForm = new FrmSomeForm())
{
    someForm.SomePropA = "A";
    someForm.SomePropB = "B";
    someForm.SomePropC = "C";
    someForm.ShowDialog();
}

我认为这是最简单的方式,在我看来更具可读性......

保持简单: - )

答案 1 :(得分:4)

using (FrmSomeForm someForm = new FrmSomeForm(){
    SomePropA = "A",
    SomePropB = "B",
    SomePropC = "C"
})
{
    someForm.ShowDialog();
}

这不起作用吗? OO

答案 2 :(得分:3)

尝试:

        using (FrmSomeForm someForm = new FrmSomeForm()
                        {
                            SomePropA = "A",
                            SomePropB = "B",
                            SomePropC = "C"
                        })
        {
            someForm.ShowDialog();
        }

答案 3 :(得分:0)

using (FrmSomeForm someForm = new FrmSomeForm()
    {
        SomePropA = "A",
        SomePropB = "B",
        SomePropC = "C"
    })
{
    someForm.ShowDialog();
}

如果您不喜欢格式化,可以执行以下操作:

using (FrmSomeForm someForm = new FrmSomeForm() { SomePropA = "A", SomePropB = "B", SomePropC = "C" })
{
    someForm.ShowDialog();
}

或者:

private FrmSomeForm InitFrmSomeForm()  
{
    return new FrmSomeForm()
    {
        SomePropA = "A",
        SomePropB = "B",
        SomePropC = "C"
    };
}

using (FrmSomeForm someForm = InitFrmSomeForm())
{
    someForm.ShowDialog();
}

答案 4 :(得分:0)

你可以这样做

using 
(
    FrmSomeForm someForm = new FrmSomeForm()
    {
        SomePropA = "A",
        SomePropB = "B",
        SomePropC = "C"
    }
)
{
     someForm.ShowDialog();
}