Convert string to boolean in C#(在 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# 中将字符串转换为布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C# 中将字符串转换为布尔值


- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01