在使用"using"块语句时使用if语句的更好方法是什么?

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)

  • 它被称为条件三元运算符:https://msdn.microsoft.com/en-us/library/zakwfxx4(v = vs.100).aspx (2认同)
  • @john - 不,它被称为条件运算符.*有些*人选择将其称为三元,因为*大多数*语言只包含一个三元运算符,它是条件运算符. (2认同)