How to use object initializers with using statements?

本小妞迷上赌 提交于 2019-12-23 17:46:00

问题


Is there any way to refactor this code to not have to use a temporary variable and still use the syntactic sugar associated with object initializers?

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

回答1:


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

doesn't this work? oO




回答2:


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

I think that is the simplest way and even the more readable in my opinion ...

Keep things simple :-)




回答3:


Try:

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



回答4:


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

If you don't like the formatting, you can do something like this:

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

Or:

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

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



回答5:


You can do it like this

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


来源:https://stackoverflow.com/questions/12922420/how-to-use-object-initializers-with-using-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!