Casting Y or N to bool C#

前端 未结 10 2193
故里飘歌
故里飘歌 2021-02-07 05:46

Just for neatness sake I was wondering, whether it\'s possible to cast Y or N to a bool? Something like this;

bool theanswer = Convert.ToBoolean(input);
         


        
10条回答
  •  醉梦人生
    2021-02-07 06:29

    Wonea gave an "IsTrue" source example from DotNetPerls. Here are two shorter versions of it:

    public static bool IsTrue(string value)
    {
        // Avoid exceptions
        if (value == null)
            return false;
    
        // Remove whitespace from string and lowercase it.
        value = value.Trim().ToLower();
    
        return value == "true"
            || value == "t"
            || value == "1"
            || value == "yes"
            || value == "y";
    }
    

    OR:

    private static readonly IReadOnlyCollection LOWER_TRUE_VALUES = new string[] { "true", "t", "1", "yes", "y" };
    
    public static bool IsTrue(string value)
    {
        return value != null
            ? LOWER_TRUE_VALUES.Contains(value.Trim().ToLower())
            : false;
    }
    

    Heck, if you want to get real short (and ugly), you can collapse that down to two lines like this:

    private static readonly IReadOnlyCollection LOWER_TRUE_VALUES = new string[] { "true", "t", "1", "yes", "y" };
    public static bool IsTrue(string value) => value != null ? LOWER_TRUE_VALUES.Contains(value.Trim().ToLower()) : false;
    

提交回复
热议问题