C# How do I check if one of two values is TRUE?

后端 未结 8 1515
梦毁少年i
梦毁少年i 2021-01-12 13:24

Should be a simple question for the C# experts here.

I basically want to check if one value or another is TRUE, a wild stab at the code is below:

if          


        
8条回答
  •  迷失自我
    2021-01-12 13:54

    A little exception checking is needed anyway. The Boolean.Parse() method gets a string as argument and returns either true or false only if the argument, once stripped out of whitespace, is equal to "True" or "False" (note capitalization). In ANY other case the function returns an exception.

    Supposing that the possible values of staff.getValue("Male") and staff.getValue("Female") are exactly those two, then the simple disjunction (||) is sufficient. If any other return value is possible, including null and the empty string, then you have to check for exceptions

    bool isMale;
    try {
        isMale = Boolean.Parse(staff.getValue("Male"));
    } catch(Exception e) {
        isMale = Boolean.False;
    }
    try {
        isFemale = Boolean.Parse(staff.getValue("Female"));
    } catch(Exception e) {
        isFemale = Boolean.False;
    }
    if (isMale || isFemale) // note double pipe ||
    {
        // do something if true
    }
    

    or compare manually

    bool isMale = Boolean.TrueValue == staff.getValue("Male");
    bool isFemale = Boolean.TrueValue == staff.getValue("Female");
    if (isMale || isFemale) // note double pipe ||
    {
        // do something if true
    }
    

提交回复
热议问题