Can .NET convert “Yes” & “No” to boolean without If?

后端 未结 12 680
情话喂你
情话喂你 2020-12-17 14:15

You would think there would be a way using DirectCast, TryCast, CType etc but all of them seem to choke on it e.g.:

CType(\"Yes\", Boolean)

12条回答
  •  误落风尘
    2020-12-17 14:45

    private static bool GetBool(string condition)
    {
        return condition.ToLower() == "yes";
    }
    
    GetBool("Yes"); // true
    GetBool("No"); // false
    

    Or another approach using extension methods

    public static bool ToBoolean(this string str)
    {
        return str.ToLower() == "yes";
    }
    
    bool answer = "Yes".ToBoolean(); // true
    bool answer = "AnythingOtherThanYes".ToBoolean(); // false
    

提交回复
热议问题