Docs-.NET-C#-指南-语言参考-关键字-值类型:bool
2024-08-23 00:06:55
ylbtech-Docs-.NET-C#-指南-语言参考-关键字-值类型:bool |
1.返回顶部 |
1、
bool(C# 参考)
- 2015/07/20
bool
关键字是 System.Boolean 的别名。 它用于声明变量来存储布尔值:true 和 false。
备注
如需支持三值逻辑(例如,在使用支持三值布尔类型的数据库时),请使用 bool?
类型。 对于 bool?
操作数,预定义的 &
和 |
运算符支持三值逻辑。 有关详细信息,请参阅布尔逻辑运算符一文的可以为 null 的布尔逻辑运算符部分。
文本
可将布尔值赋给 bool
变量。 也可以将计算结果为 bool
类型的表达式赋给 bool
变量。
C#复制
public class BoolTest
{
static void Main()
{
bool b = true; // WriteLine automatically converts the value of b to text.
Console.WriteLine(b); int days = DateTime.Now.DayOfYear; // Assign the result of a boolean expression to b.
b = (days % == ); // Branch depending on whether b is true or false.
if (b)
{
Console.WriteLine("days is an even number");
}
else
{
Console.WriteLine("days is an odd number");
}
}
}
/* Output:
True
days is an <even/odd> number
*/
bool
变量的默认值为 false
。 bool?
变量的默认值为 null
。
转换
在 C++ 中,bool
类型的值可转换为 int
类型的值;也就是说,false
等效于零值,而 true
等效于非零值。 在 C# 中,不存在 bool
类型与其他类型之间的相互转换。 例如,下面的 if
语句在 C# 中无效:
C#复制
int x = ; // if (x) // Error: "Cannot implicitly convert type 'int' to 'bool'"
{
Console.Write("The value of x is nonzero.");
}
若要测试 int
类型的变量,必须将该变量与一个值(例如零)进行显式比较,如下所示:
C#复制
if (x != ) // The C# way
{
Console.Write("The value of x is nonzero.");
}
示例
在此例中,你通过键盘输入一个字符,然后程序检查输入的字符是否是一个字母。 如果字符是一个字母,则程序检查它是大写还是小写。 执行这些检查使用的是 IsLetter 和 IsLower,二者均返回 bool
类型:
C#复制
public class BoolKeyTest
{
static void Main()
{
Console.Write("Enter a character: ");
char c = (char)Console.Read();
if (Char.IsLetter(c))
{
if (Char.IsLower(c))
{
Console.WriteLine("The character is lowercase.");
}
else
{
Console.WriteLine("The character is uppercase.");
}
}
else
{
Console.WriteLine("Not an alphabetic character.");
}
}
}
/* Sample Output:
Enter a character: X
The character is uppercase. Enter a character: x
The character is lowercase. Enter a character: 2
The character is not an alphabetic character.
*/
C# 语言规范
有关详细信息,请参阅 C# 语言规范。 该语言规范是 C# 语法和用法的权威资料。
请参阅
2、
2.返回顶部 |
3.返回顶部 |
4.返回顶部 |
5.返回顶部 |
1、
2、
6.返回顶部 |
作者:ylbtech 出处:http://ylbtech.cnblogs.com/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 |
最新文章
- 我的屌丝giser成长记-研二篇
- Oracle在中文环境下出现乱码解决办法
- jpg转png
- JavaScript中的继承(原型链)
- HtmlAgilityPackage XPath学习
- In App Purchase翻译
- 解决rhel相关系统下yum找不到安装包的解决方法
- 当当开源sharding-jdbc,轻量级数据库分库分表中间件
- javaWEB总结(15):jsp指令_page指令
- android log 学习
- 翻译-你必须知道的28个HTML5特征、窍门和技术
- 关于transform的3D变形函数
- TsinsenA1489 抽奖 【期望】
- 小P的金字塔
- springboot logback 集成
- 2015年第六届蓝桥杯JavaB组省赛试题解析
- 安卓项目R,java文件不能自动更新,clean之后,R.java消失 (转自 Cynosure鱼)
- 【SQL】185. Department Top Three Salaries
- Dynamics CRM 2011 权限管理
- POJ 1064 Cable master (二分查找)
热门文章
- h5中history实例
- 剑指Offer(三十六):两个链表的第一个公共结点
- ted演讲小总结(持续更新_12月15日)
- PCL安装与配置
- LightOJ - 1173 - The Vindictive Coachf(DP)
- SpringBoot官方文档学习(三)配置文件、日志、国际化和JSON
- shiro认证+盐加密
- centOS下实践查询版本/CPU/内存/硬盘容量等硬件信息
- 洛谷 P1279 字串距离 题解
- codevs:2849 素数判定 3:输入一个正整数x(3<;=x<;=100000),判断x是否是质数,如果是质数则输出信息“prime”,否则输出“composite”。