问题
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