简单类型属于C# 语言的值类型,对应于C++语言的基本类型,包括字符、布尔类型、以及整数和实数等数值类型。与C++/CLI相似,C# 中的基本类型都与.NET框架的System命名空间中的对应类型等同,是它们的别名。参见下表:C# 的简单类型C#类型C++/CLI类型.NET框架类型值类型字节/位数范围和精度bool boolSystem.Boolean 真或假-/1true或falsechar wchar_tSystem.Char 字符2/16所有UTF-16编码(0~0xFFFF)sbyte[signed] charSystem.SByte 整数1/8-128 ~ 127byteunsigned charSystem.Byte 1/80 ~ 255short [signed] shortSystem.Int16 2/16-32 768 ~ 32 767ushort unsigned shortSystem.UInt16 2/160 ~ 65 535int[signed] int/longSystem.Int32 4/32-2 147 483 648 ~ 2 147 483 647uintunsigned int/longSystem.UInt32 4/320 ~ 4 294 967 295long[signed] long longSystem.Int64 8/64-9 223 372 036 854 775 808~ 9 223 372 036 854 775 807ulong unsigned long longSystem.UInt64 8/640 ~ 18 446 744 073 709 551 615float float System.Single 浮点数4/32±1.5×10-45 ~ ±3.4×1038doubledoubleSystem.Double 8/64±5.0×10-324 ~ ±1.7×10308decimal DecimalSystem.Decimal 高精度十进制小数16/128±1.0×10-28 ~ ±7.9×1028其中的sbyte、byte、short、ushort、int、uint、long、ulong和char等9种类型被为整数类型(integral types)。可见,C# 的简单类型的名称,比C++的更简洁明了。如signed被省略;unsigned简写成了u,从而unsigned short、unsigned int和unsigned long long分别被改成了ushort 、uint和ulong;char对应于C++的wchar_t;sbyte部分对应于C++的char,但是sbyte只表示单字节的有符号整数,不再表示单字节的普通字符,因为在C# 不支持单字节字符。因此,在C# 中,不再需要C++中的L"……"运算符来进行普通字符串常量向宽字符串的转换。与C++非常不同等一点是,C# 中所有×××类型(如int和long)的字节数都是固定的,不再像C/C++那样依赖于CPU的字长。还有几点与C++不同,但是与C++/CLI相同的是:l 可以用(从System.Object继承的)GetType()方法来获得指定变量或对象的类型名称。简单类型返回的是.NET的类型名,对象则返回类或结构的名称。例如:int i = 1;
MyClass obj;
Console::WriteLine(L"The type of variable i is {0} and object obj is {1}.", i.GetType(), obj->GetType());
的输出为:The type of variable i is System.Int32 and the object obj is MyClass.l 具有.NET的高精度十进制小数类型System.Decimal的对应类型decimal。在C# 中可以用m或M后缀,将一个实数常量指定为decimal类型。没有后缀的实数会被视为double类型,直接赋值给decimal变量会导致编译错误。例如:decimal money = 1234.5m; // 正确
decimal d = 1234.5; // 编译错误注意:在C++/CLI中没有类似的后缀指示符,需要用Decimal的构造函数。例如:// C++/CLI例
decimal d = 1234.5; // 编译错误
Decimal money = Decimal(1234.5); // 正确