清除为可空布尔值编写代码的方法

时间:2012-12-07 16:12:07

标签: c# asp.net nullable

是否有更简洁的方法来编写此代码。我觉得可能有,但我不知道如何。

    if (loadedFormData.Education.AwardedADegree==true)
    {
        this.radiobuttonNoAwarded.Checked = false;
        this.radiobuttonYesAwarded.Checked = true;
    }
    if (loadedFormData.Education.AwardedADegree == false)
    {
        this.radiobuttonNoAwarded.Checked = true;
        this.radiobuttonYesAwarded.Checked = false;
    }
    else // AwardedADegree is null
    {
        this.radiobuttonNoAwarded.Checked = false;
        this.radiobuttonYesAwarded.Checked = false;

    }

4 个答案:

答案 0 :(得分:11)

提出问题“我的radiobutton何时应该被检查”,而不是“当我的数据为真/假/空时会发生什么”。

this.radiobuttonNoAwarded.Checked = loadedFormData.Education.AwardedADegree == false;
this.radiobuttonYesAwarded.Checked =  loadedFormData.Education.AwardedADegree == true;

答案 1 :(得分:5)

我假设bool?允许该值为空。

this.radiobuttonNoAwarded.Checked = AwardedADegree.HasValue && AwardedADegree.Value;
this.radiobuttonYesAwarded.Checked = AwardedADegree.HasValue && !AwardedADegree.Value;

答案 2 :(得分:1)

试试这个:

 this.radiobuttonNoAwarded.Checked = (!loadedFormData.Education.AwardedADegree) ?? false;
 this.radiobuttonYesAwarded.Checked = loadedFormData.Education.AwardedADegree ?? false;

答案 3 :(得分:0)

this.radiobuttonNoAwarded.Checked = (loadedFormData.Education.AwardedADegree ?? false);
this.radiobuttonYesAwarded.Checked = !(loadedFormData.Education.AwardedADegree ?? true);