對於char,這個字符類型。我們一般都認為就是一個字節。今天在仔細比較發現,C#的char和C++的char是有區別的。
1.首先來看C#中char占多大空間
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(sizeof(char));
Console.Read();
}
}
}
居然是返回2.也就是說兩個字節。
2. 在C++中呢?
#include <iostream>
using namespace std;
int main()
{
cout << sizeof(char)<<endl;
return 0;
}
這里看到的結果是顯示為1個字節
但是同時,我又想起來,C++里面還有另外一個char類型,也就是所謂的wchar_t,通常用來表示unicode char,它的空間是多少呢?
#include <iostream>
using namespace std;
int main()
{
cout << sizeof(wchar_t)<<endl;
return 0;
}
3. 那么,是不是說C#中的char都是表示unicode字符的呢?
沒錯,就是這樣. 如此才能解釋得通嘛
http://msdn.microsoft.com/zh-cn/library/x9h8tsay.aspx
char 關鍵字用於聲明下表所示范圍內的 Unicode 字符。Unicode 字符是 16 位字符,用於表示世界上大多數已知的書面語言。
| 類型 |
范圍 |
大小 |
.NET Framework 類型 |
|---|---|---|---|
| char |
U+0000 到 U+ffff |
16 位 Unicode 字符 |
4. 題外話:SQL Server 中的字符類型
我還想到,在SQL Server的類型系統中有下面幾個字符類型,大家也要有所比較
| 定長 | char |
| 定長(unicode) | nchar |
| 變長 | varchar |
| 變長(unicode) | nvarchar |
也就是說,在SQL Server中也是明確地區分unicode和非unicode的



