You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将C#中的If Else代码改写为三元条件运算符?

使用三元条件运算符改写C#条件判断代码

你的原代码可以拆分为两部分处理:布尔属性的二元状态赋值和仅在分支内执行的额外操作,用三元运算符改写后更简洁,同时保证可读性:

推荐写法(清晰易维护)

// 直接用条件表达式的布尔结果赋值,替代冗余的三元写法
metroContextMenuStrip1.Enabled = B_21_GDV_Variant.RowCount > 0;
B_21_GDV_Variant.AllowDeleting = !(B_21_GDV_Variant.RowCount > 0);

// 仅当RowCount>0时执行列格式设置,这部分无法用三元优雅替代,保留if判断
if (B_21_GDV_Variant.RowCount > 0)
{
    B_21_GDV_Variant.Columns["HB"].Format = "{0:N}";
    B_21_GDV_Variant.Columns["HB"].CellStyle.HorizontalAlignment = HorizontalAlignment.Left;
}

说明

  • 对于Enabled和AllowDeleting这类布尔属性,它们的取值正好是条件的布尔结果(或其取反),直接赋值即可,不需要写condition ? true : false这种冗余的三元表达式。
  • 列格式设置仅在RowCount>0时执行,else分支无对应操作,用单独的if判断比强行塞进三元运算符更清晰,避免可读性下降。

不推荐的“全三元”写法(仅作演示)

如果一定要把所有操作都用三元运算符(不建议,可读性差),可以利用C#7+的元组逗号表达式,但需要接收无意义的返回值:

metroContextMenuStrip1.Enabled = B_21_GDV_Variant.RowCount > 0;
B_21_GDV_Variant.AllowDeleting = !(B_21_GDV_Variant.RowCount > 0);

// 用三元执行多语句操作,需接收返回值(用下划线忽略)
_ = B_21_GDV_Variant.RowCount > 0 ? (
    B_21_GDV_Variant.Columns["HB"].Format = "{0:N}",
    B_21_GDV_Variant.Columns["HB"].CellStyle.HorizontalAlignment = HorizontalAlignment.Left
) : default;

内容的提问来源于stack exchange,提问作者Philipe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 00:15:35