Casting Y or N to bool C#

前端 未结 10 2389
故里飘歌
故里飘歌 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条回答
  •  旧时难觅i
    2021-02-07 06:10

    DotNetPerls has a handy class for parsing various string bools.

    /// 
    /// Parse strings into true or false bools using relaxed parsing rules
    /// 
    public static class BoolParser
    {
        /// 
        /// Get the boolean value for this string
        /// 
        public static bool GetValue(string value)
        {
           return IsTrue(value);
        }
    
        /// 
        /// Determine whether the string is not True
        /// 
        public static bool IsFalse(string value)
        {
           return !IsTrue(value);
        }
    
        /// 
        /// Determine whether the string is equal to True
        /// 
        public static bool IsTrue(string value)
        {
           try
           {
                // 1
                // Avoid exceptions
                if (value == null)
                {
                    return false;
                }
    
                // 2
                // Remove whitespace from string
                value = value.Trim();
    
                // 3
                // Lowercase the string
                value = value.ToLower();
    
                // 4
                // Check for word true
                if (value == "true")
                {
                    return true;
                }
    
                // 5
                // Check for letter true
                if (value == "t")
                {
                    return true;
                }
    
                // 6
                // Check for one
                if (value == "1")
                {
                    return true;
                }
    
                // 7
                // Check for word yes
                if (value == "yes")
                {
                    return true;
                }
    
                // 8
                // Check for letter yes
                if (value == "y")
                {
                    return true;
                }
    
                // 9
                // It is false
                return false;
            }
            catch
            {
                return false;
            }
        }
    }
    

    Is called by;

    BoolParser.GetValue("true")
    BoolParser.GetValue("1")
    BoolParser.GetValue("0")
    

    This could probably be further improved by adding a parameter overload to accept an object.

提交回复
热议问题