Ani*_*ish 4 c# if-statement operators instance winforms
我有一个场景,我有两个新对象,其中只有一个必须根据条件初始化.
但我正在使用"using"块语句来初始化一个新对象.
我怎样才能实现它?请参考以下方案.
int a;
string b;
if()//some codition
{
using(MyClass c1 = new MyClass(a))
{
SomeMethod();
}
}
else
{
using(MyClass c1 = new MyClass(b)
{
SomeMethod();
}
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来实现单一条件或任何其他方式来减少代码?因为我在两种情况下都调用相同的方法.
提前致谢.
此致,Anish
小智 6
您可以使用条件(三元)运算符.
int a;
string b;
using(MyClass c1 = (some condition) ? new MyClass(a) : new MyClass(b))
{
SomeMethod();
}
Run Code Online (Sandbox Code Playgroud)