Convert string to boolean in C#

后端 未结 2 1932
长情又很酷
长情又很酷 2020-12-16 11:10

I need help converting a string to a bool value:

I\'ve been trying to get the value (true or false) from the TopMost for my program and save it in my settings.

2条回答
  •  生来不讨喜
    2020-12-16 12:13

    You must use some of the C # conversion systems:

    string to boolean: True to true

    string str = "True";
    bool mybool = System.Convert.ToBoolean(str);
    

    boolean to string: true to True

    bool mybool = true;
    string str = System.Convert.ToString(mybool);
    
    //or
    
    string str = mybool.ToString();
    

    bool.Parse expects one parameter which in this case is str, even .

    Convert.ToBoolean expects one parameter.

    bool.TryParse expects two parameters, one entry (str) and one out (result).

    If TryParse is true, then the conversion was correct, otherwise an error occurred

    string str = "True";
    bool MyBool = bool.Parse(str);
    
    //Or
    
    string str = "True";
    if(bool.TryParse(str, out bool result))
    {
       //Correct conversion
    }
    else
    {
         //Incorrect, an error has occurred
    }
    

提交回复
热议问题