TOC

This article is currently in the process of being translated into Chinese (~78% done).

数据类型:

The Char type

System.Char数据类型用于操作一个单独的,unicode字符。C#中此类的别名是char,可用于定义char类型的变量:

char ch;

当然,也可以在定义时赋值。C#中,char常量由一对单引号引起来:

char ch = 'H';

由于字符串(将在下一章介绍)的本质就是一串字符,.NET实际上就是用一个字符列表来表示字符串的。这也表示可以从字符串中取得单个字符,或者可以通过迭代从字符串中以字符类型取出每个字符:

string helloWorld = "Hello, world!";
foreach(char c in helloWorld)
{
    Console.WriteLine(c);
}

在后台,字符实际上是以数字表示的,其中每个字符对应Unicode“字母表”内的一个数字。截止写作本文前,总共有超过130.000多个不同的Unicode字符,从拉丁/西方字母表到历史脚本。因此,在C#中,很容易通过字符获得其数字值,下面把前面例子稍加修改来演示这一点:

string helloWorld = "Hello, world!";
foreach(char c in helloWorld)
{
    Console.WriteLine(c + ": " + (int)c);
}

此例子会简单地输出字符,然后是其对应的数字,只简单地用类型强制转换把其由char类型变为integer类型。这也表示反之亦然:从数字同样可以转变为字符。不过为何要这样做呢?因为,有很多字符在多数键盘上是没有的,如,版权字符(©)。可以改用Unicode查找表找到所需字符的数字版本,然后把其转变为字符:

char ch = (char)169;
Console.WriteLine(ch);

Char类型的辅助方法

Char类有一些很好的辅助方法,有助于确定当前操作的字符的类型。这在很多情况下都很有用,如,输入合法性验证时。示例:

Console.WriteLine("Enter a single number:");
char ch = Console.ReadKey(true).KeyChar;
if (Char.IsDigit(ch))
    Console.WriteLine("Thank you!");
else
    Console.WriteLine("Wrong - please try again!");

这里简单地读入用户敲入的第一个键,然后用Char.IsDigit()方法来检查其是否是个数字。还有很多象这个一样的方法可用来检查字符的类型。这可用于对字符串的简单较验:

Console.WriteLine("Write your name:");
string name = Console.ReadLine();  
bool isValid = true;  
for(int i = 0; i < name.Length; i++)  
{  
    char ch = name[i];  
    if((i == 0) && ((!Char.IsLetter(ch)) || (!Char.IsUpper(ch))))  
    {  
Console.WriteLine("The first character has to be an uppercase letter!");  
isValid = false;  
break;  
    }  
    if(Char.IsDigit(ch))  
    {  
Console.WriteLine("No digits allowed!");  
isValid = false;  
break;  
    }  
}  
if (isValid)  
    Console.WriteLine("Hello, " + name);

上例简单地对用户输入的姓名进行迭代,使用不同版本的Is*方法来检查输入与当前的简单需求是否符合。还有一些有用的方法,就象Char.IsLetterOrDigit()方法。全部的方法列表请参考文档

总结

char类型(System.Char类的别名)用于表示一个单独的Unicode字符。要表示多个字符,可以使用字符串,其本质上只是字符的一个列表。下一章将介绍字符串。


This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!