3

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

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

5 回答 5

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

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

保持简单:-)

于 2012-10-16T19:56:12.007 回答
5
using (FrmSomeForm someForm = new FrmSomeForm(){
    SomePropA = "A",
    SomePropB = "B",
    SomePropC = "C"
})
{
    someForm.ShowDialog();
}

这不行吗?oO

于 2012-10-16T19:54:27.007 回答
3

尝试:

        using (FrmSomeForm someForm = new FrmSomeForm()
                        {
                            SomePropA = "A",
                            SomePropB = "B",
                            SomePropC = "C"
                        })
        {
            someForm.ShowDialog();
        }
于 2012-10-16T19:55:13.447 回答
0

你可以这样做

using 
(
    FrmSomeForm someForm = new FrmSomeForm()
    {
        SomePropA = "A",
        SomePropB = "B",
        SomePropC = "C"
    }
)
{
     someForm.ShowDialog();
}
于 2012-10-16T19:57:24.480 回答
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();
}
于 2012-10-16T19:55:46.643 回答