winforms 三元条件运算符If Else C#

ct2axkht  于 2022-12-14  发布在  C#
关注(0)|答案(3)|浏览(187)

我写了这段代码:

if (B_21_GDV_Variant.RowCount > 0)
        {
            metroContextMenuStrip1.Enabled = true;
            B_21_GDV_Variant.AllowDeleting = false;
            B_21_GDV_Variant.Columns["HB"].Format = "{0:N}";
            B_21_GDV_Variant.Columns["HB"].CellStyle.HorizontalAlignment = HorizontalAlignment.Left;
        }
        else
        {
            metroContextMenuStrip1.Enabled = false;
            B_21_GDV_Variant.AllowDeleting = true;
        }

我只想知道,如何用三元条件运算符来写它?

aamkag61

aamkag611#

一般情况下,在这种情况下可能不推荐使用,但仍然可以使用。不仅三元条件运算符,而且还可以使用直接的布尔值来设置。这就是:

metroContextMenuStrip1.Enabled = (B_21_GDV_Variant.RowCount > 0);
B_21_GDV_Variant.AllowDeleting = !(B_21_GDV_Variant.RowCount > 0);
B_21_GDV_Variant.Columns["HB"].Format = (B_21_GDV_Variant.RowCount > 0) ? "{0:N}" : B_21_GDV_Variant.Columns["HB"].Format;
B_21_GDV_Variant.Columns["HB"].CellStyle.HorizontalAlignment = (B_21_GDV_Variant.RowCount > 0) ? HorizontalAlignment.Left : B_21_GDV_Variant.Columns["HB"].CellStyle.HorizontalAlignment;

我不建议在这种情况下使用三元条件运算符,因为它对可读性没有帮助,而且通常在这种情况下使用它不会产生任何性能改进。

9nvpjoqh

9nvpjoqh2#

如果你想强制使用三进制,并且你想获得一些可读性,那么我建议你这样做:

var data = 
    B_21_GDV_Variant.RowCount > 0
    ? (
        Enabled: true,
        AllowDeleting: false,
        Format: "{0:N}",
        HorizontalAlignment: HorizontalAlignment.Left
    )
    : (
        Enabled: false,
        AllowDeleting: true,
        Format: B_21_GDV_Variant.Columns["HB"].Format,
        HorizontalAlignment: B_21_GDV_Variant.Columns["HB"].CellStyle.HorizontalAlignment
    );

metroContextMenuStrip1.Enabled = data.Enabled;
B_21_GDV_Variant.AllowDeleting = data.AllowDeleting;
B_21_GDV_Variant.Columns["HB"].Format = data.Format;
B_21_GDV_Variant.Columns["HB"].CellStyle.HorizontalAlignment = data.HorizontalAlignment;
y53ybaqx

y53ybaqx3#

最接近的形式是:

_ = (B_21_GDV_Variant.RowCount > 0)
    ? new Func<bool>(() => 
    {
        metroContextMenuStrip1.Enabled = true;
        B_21_GDV_Variant.AllowDeleting = false;
        B_21_GDV_Variant.Columns["HB"].Format = "{0:N}";
        B_21_GDV_Variant.Columns["HB"].CellStyle.HorizontalAlignment = HorizontalAlignment.Left;
        return true;
    })()
    : new Func<bool>(() => 
    {
        metroContextMenuStrip1.Enabled = false;
        B_21_GDV_Variant.AllowDeleting = true;
        return false;
    })();

也就是说,三元运算符必须返回一个值,而这个值在这里被丢弃(见下划线)。
Package 更多操作的解决方案是将它们包含在一个委托中(本例中为Func),然后立即执行(请参见每个块最后的括号对)。
技术上可行,但老实说,我看不出这样做有什么方便。

相关问题