5

我将信息显示为ThreeState启用的复选框,并希望以最简单的方式使用可为空的布尔值。

目前我正在使用嵌套的三元表达式;但有更清晰的方法吗?

bool? foo = null;
checkBox1.CheckState = foo.HasValue ?
    (foo == true ? CheckState.Checked : CheckState.Unchecked) :
    CheckState.Indeterminate;

* 请注意,复选框和表单是只读的。

4

3 回答 3

6

我就是这样做的。

我会添加一个扩展方法来清理它。

    public static CheckState ToCheckboxState(this bool booleanValue)
    {
        return booleanValue.ToCheckboxState();
    }

    public static CheckState ToCheckboxState(this bool? booleanValue)
    {
        return booleanValue.HasValue ?
               (booleanValue == true ? CheckState.Checked : CheckState.Unchecked) :
               CheckState.Indeterminate;
    }
于 2012-04-27T20:17:46.377 回答
3

更清楚的是一个有争议的陈述。例如,我可以说这更清楚。

if(foo.HasValue)
{
    if(foo == true) 
       checkBox1.CheckState = CheckState.Checked;
    else
       checkBox1.CheckState = CheckState.Unchecked;
}
else
    checkBox1.CheckState  = CheckState.Indeterminate;

另一种选择是为此创建一个方法:

checkBox1.CheckState = GetCheckState(foo);

public CheckState GetCheckState(bool? foo)
{
    if(foo.HasValue)
    {
        if(foo == true) 
           return CheckState.Checked;
        else
           return CheckState.Unchecked;
    }
    else
        return CheckState.Indeterminate

}

但是我喜欢你的代码。

于 2012-04-27T20:20:25.200 回答
0

基于@Nathan对扩展方法的建议,我想出了这个:

public static void SetCheckedNull(this CheckBox c, bool? Value)
{
    if (!c.ThreeState)
        c.Checked = Value == true;
    else
        c.CheckState = Value.HasValue ?
            (Value == true ? CheckState.Checked : CheckState.Unchecked) :
            CheckState.Indeterminate;
}

我唯一不喜欢的是,在设置“正常”复选框时:

checkBox1.Checked = someBool;

与设置启用 ThreeState 的复选框相比:

checkBox2.SetCheckedNull(someNullableBool);

后者只是感觉不同,它稍微调整了强迫症。:)

于 2012-04-27T20:30:48.557 回答