当前位置: 移动技术网 > IT编程>开发语言>c# > C# 中的 bool、char 和 string 类型

C# 中的 bool、char 和 string 类型

2019年12月15日  | 移动技术网IT编程  | 我要评论
上一篇(地址: "https://www.vinanysoft.com/c sharp basics/data types/fundamental numeric types/" )只介绍了基本数值类型,本篇将介绍其他的一些类型: 、`char string`。 布尔类型( ) 关键字是 的别名。 ...

上一篇(地址:)只介绍了基本数值类型,本篇将介绍其他的一些类型: boolcharstring

布尔类型(bool

bool 关键字是 system.boolean 的别名。 它用于声明变量来存储布尔值:truefalse

可将布尔值赋给 bool 变量。 也可以将计算结果为 bool 类型的表达式赋给 bool 变量。

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 % 2 == 0);

        // 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 实际大小是一个字节。

字符类型(char

char 类型关键字是 system.char 结构类型的别名,它表示 unicode utf-16 字符:

类型 范围 大小 .net 类型
char u+0000 到 u+ffff 16 位 system.char

输入 char 字面量需要将字符放到一对单引号中,比如 'a'。所有键盘字符都可这样输入,包括字母、数字以及特殊符号。

有的字符不能直接插入源代码,需进行特殊处理。首先输入反斜杠(\)前缀,再跟随一个特殊字符代码。反斜杠和特殊字符代码统称为转义序列(escape sequence)。

例如,\n 代表换行符,而 \t 代表制表符。由于反斜杠标志转义序列开始,所以要用 \\ 表示反斜杠字符。

console.write("\'");    //输出单引号(')
console.write("\\");    //输出反斜杠(\)

char 类型字面量可以输入字符、十六进制转义序列或 unicode 表示形式。 也可以将整型字面量强制转换为相应的 char 值。 在下面的示例中,使用相同的字符 xchar 数组的四个元素进行初始化:

var chars = new char[4];

chars[0] = 'x';        // character literal
chars[1] = '\x0058';   // hexadecimal
chars[2] = (char)88;   // cast from integral type
chars[3] = '\u0058';   // unicode

console.write(string.join(" ", chars));
// output: x x x x

下表列出了字符串转义序列:

转义序列 字符名称 unicode 编码
\' 单引号 0x0027
\" 双引号 0x0022
\\ 反斜杠 0x005c
\0 null 0x0000
\a 警报 0x0007
\b 退格 0x0008
\f 换页 0x000c
\n 换行 0x000a
\r 回车 0x000d
\t 水平制表符 0x0009
\v 垂直制表符 0x000b
\u unicode 转义序列 (utf-16) \uhhhh(范围:0000 - ffff;示例:\u00e7 =“ç”)
\u unicode 转义序列 (utf-32) \u00hhhhhh(范围:000000 - 10ffff;示例:\u0001f47d =“

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网