代码之家  ›  专栏  ›  技术社区  ›  wonea Ilya Smagin

将Y或N转换为布尔C#

  •  18
  • wonea Ilya Smagin  · 技术社区  · 14 年前

    只是为了整洁,我在想,是不是可以把Y或N抛给一个布尔?像这样的东西;

    bool theanswer = Convert.ToBoolean(input);
    

    bool theanswer = false;
    switch (input)
    {
       case "y": theanswer = true; break;
       case "n": theanswer = false; break
    }
    
    10 回复  |  直到 14 年前
        1
  •  44
  •   Jon Skeet    14 年前

    不,这里面没有什么东西。

    但是,如果希望默认为false,则可以使用:

    bool theAnswer = (input == "y");
    

    (括号只是为了清楚起见。)

    bool theAnswer = "y".Equals(input, StringComparison.OrdinalIgnoreCase);
    

    请注意,使用指定的字符串比较可以避免创建新字符串,并且意味着您不需要担心文化问题。。。除非你 希望 当然,要进行文化敏感性比较。还要注意,我已经将文本作为方法调用的“目标”来避免 NullReferenceException 什么时候被扔 input null .

        2
  •  8
  •   Joel Etherton    14 年前
    bool theanswer = input.ToLower() == "y";
    
        3
  •  5
  •   Richard J. Ross III    14 年前

    为字符串创建一个扩展方法,该方法执行与第二个算法中指定的类似的操作,从而清理代码:

    public static bool ToBool(this string input)
    {
        // input will never be null, as you cannot call a method on a null object
        if (input.Equals("y", StringComparison.OrdinalIgnoreCase))
        {
             return true;
        }
        else if (input.Equals("n", StringComparison.OrdinalIgnoreCase))
        {
             return false;
        }
        else
        {
             throw new Exception("The data is not in the correct format.");
        }
    }
    

    并调用代码:

    if (aString.ToBool())
    {
         // do something
    }
    
        4
  •  5
  •   wonea Ilya Smagin    9 年前

    正如乔恩所建议的,没有什么是内在的。约翰贴出的答案给了你一个正确的方法。欲了解更多详情,请访问:

    http://msdn.microsoft.com/en-us/library/86hw82a3.aspx link text

        5
  •  4
  •   this. __curious_geek    14 年前

    这个怎么样。

    bool theanswer = input.Equals("Y", StringComparison.OrdinalIgnoreCase);
    

    或者更安全的版本。

    bool theanswer = "Y".Equals(input, StringComparison.OrdinalIgnoreCase);
    
        6
  •  0
  •   Xander    14 年前

    bool CastToBoolean(string input)
    {
        return input.Equals("Y", StringComparison.OrdinalIgnoreCase);
    }
    
        7
  •  0
  •   niranjan    10 年前

    bool b=true; 
            decimal dec; 
            string CurLine = "";        
            CurLine = sr.ReadLine();
            string[] splitArray = CurLine.Split(new Char[] { '=' });
            splitArray[1] = splitArray[1].Trim();
            if (splitArray[1].Equals("Y") || splitArray[1].Equals("y")) b = true; else b = false;
            CurChADetails.DesignedProfileRawDataDsty1.Commen.IsPad = b;
    
        8
  •  0
  •   wonea Ilya Smagin    9 年前

    DotNetPerls 有一个方便的类来解析各种字符串bool。

    /// <summary>
    /// Parse strings into true or false bools using relaxed parsing rules
    /// </summary>
    public static class BoolParser
    {
        /// <summary>
        /// Get the boolean value for this string
        /// </summary>
        public static bool GetValue(string value)
        {
           return IsTrue(value);
        }
    
        /// <summary>
        /// Determine whether the string is not True
        /// </summary>
        public static bool IsFalse(string value)
        {
           return !IsTrue(value);
        }
    
        /// <summary>
        /// Determine whether the string is equal to True
        /// </summary>
        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;
            }
        }
    }
    

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

    通过添加一个参数重载来接受一个对象,这可能会得到进一步的改进。

        9
  •  0
  •   Community CDub    8 年前

    Wonea gave an "IsTrue" source example from DotNetPerls. 这里有两个简短的版本:

    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";
    }
    

    或:

    private static readonly IReadOnlyCollection<string> 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;
    }
    

    private static readonly IReadOnlyCollection<string> 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;
    
        10
  •  -1
  •   Ubaid    14 年前
    class Program
    {
        void StringInput(string str)
        {
            string[] st1 = str.Split(' ');
    
            if (st1 != null)
            {
                string a = str.Substring(0, 1);
                string b=str.Substring(str.Length-1,1);
    
                 if(
                    a=="^" && b=="^" 
                    || a=="{" && b=="}" 
                    || a=="[" && b=="]"
                    ||a=="<" && b==">" 
                    ||a=="(" && b==")"
                    )
    
                {
                    Console.Write("ok Formate correct");
                }
                else
                {
                    Console.Write("Sorry incorrect formate...");
                }
            }
        }
        static void Main(string[] args)
        {
            ubaid: ;
            Program one = new Program();
            Console.Write("For exit Press N ");
            Console.Write("\n");
            Console.Write("Enter your value...=");
            string ub = Console.ReadLine();
    
            if (ub == "Y" || ub=="y" || ub=="N" || ub=="n" )
            {
                Console.Write("Are your want to Exit Y/N: ");
                string ui = Console.ReadLine();
                if (ui == "Y" || ui=="y")
                {
                    return;
                }
                else
                {
                    goto ubaid;
                }
    
            }
            one.StringInput(ub);           
            Console.ReadLine();
            goto ubaid;
        }
    }