在C#中将字符串转换为布尔值 [英] Convert string to boolean in C#

查看:1052
本文介绍了在C#中将字符串转换为布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助将字符串转换为bool值:

I need help converting a string to a bool value:

我一直在尝试从TopMost中为程序获取值(真或假)并将其保存在我的设置中.

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

Settings1.Default["tm"] = ;
Settings1.Default.Save();

我的设置'tm'的类型是布尔值(true,false) 但是我只是在短时间内使用C#,而且我不确定如何保存TopMost是对还是错.

The type for my setting 'tm' is a bool value (true, false) but I've only been using C# for a short amount of time and I'm not sure how to save whether or not my TopMost will be true or false.

在您说要在属性中使用一个之前,它是一个用户选项;我希望他们能够选择打开(true)还是关闭(false)选项,但将其保存并加载为bool值.

Before you say to use the one in properties it's a user option; I want them to be able to choose the option of whether it's on(true) or off(false) but have it save and load as a bool value.

推荐答案

我知道这不是一个理想的答案,但是由于OP似乎是初学者,所以我很想与他分享一些基本知识.希望大家都能理解

I know this is not an ideal question to answer but as the OP seems to be a beginner, I'd love to share some basic knowledge with him... Hope everybody understands

OP,您可以使用以下任何一种方法将字符串转换为Boolean类型:

OP, you can convert a string to type Boolean by using any of the methods stated below:

 string sample = "True";
 bool myBool = bool.Parse(sample);

 ///or

 bool myBool = Convert.ToBoolean(sample);

bool.Parse期望一个参数,在这种情况下为sample.ToBoolean也期望一个参数.

bool.Parse expects one parameter which in this case is sample, .ToBoolean also expects one parameter.

您可以使用与Parse相同的TryParse,但不会引发任何异常:)

You can use TryParse which is the same as Parse but it doesn't throw any exception :)

  string sample = "false";
  Boolean myBool;

  if (Boolean.TryParse(sample , out myBool))
  {
  }

请注意,您不能将任何类型的字符串转换为类型Boolean,因为Boolean的值只能是TrueFalse

Please note that you cannot convert any type of string to type Boolean because the value of a Boolean can only be True or False

希望您能理解:)

这篇关于在C#中将字符串转换为布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆