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# 中将字符串转换为布尔值
基础教程推荐
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- 将数据集转换为列表 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- 如果条件可以为空 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
