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

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

问题描述

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

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' 的类型是布尔值(真、假)但我只使用 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.

在您说使用属性中的那个之前,它是一个用户选项;我希望他们能够选择是 on(true) 还是 off(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.

您可以使用 TryParse,它与 Parse 相同,但不会抛出任何异常:)

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))
{
    // Do Something
}

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

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天全站免登陆