看的是英文的MSDN,笔记用中文翻译--提醒自己要把英文和中文一起提高。
一个类型定义包含以下信息:
1)这个类型的变量所需的存储空间
2)此类型的变量能够表示的最大值最小值
3)此类型包含的成员(方法、域、事件等等)
4)此类型的父类型
5)在运行时,在内存中变量的指定位置
6)允许的操作符
一旦一个变量被声明了,它将不能被声明为另一个类型,或者不能指定的一个不能被自动转化为其类型的值。
C#中的数据类型由以下几种构成:
1)内置数据类型(build-in type),这些数据类型是System名字空间下的预定义类型的简称。其中除了object、string类型外,其它的都被归为简单数据类型。这些类型包括:
C# Type | .Net Framework Type |
bool | System.Boolean |
byte | System.Byte |
sbyte | System.SByte |
char | System.Char |
decimal | System.Decimal |
double | System.Double |
float | System.Float |
int | System.Int32 |
uint | System.UInt32 |
long | System.Int64 |
ulong | System.UInt64 |
object | System.Object |
short | System.Int16 |
ushort | System.UInt16 |
string | System.String |
即定义一个变量时,如下两种是相同的:
int x = 124;
System.Int32 x = 124;
用方法GetType()获取一个变量的类型,如下:
Console.WriteLine(myVariable.GetType());
2)集成的数据类型(integral type),由内置数据类型中的简单类型组成,包括如下几种:
Type | Range | Size |
-128 to 127 | Signed 8-bit integer | |
0 to 255 | Unsigned 8-bit integer | |
U+0000 to U+ffff | Unicode 16-bit character | |
-32,768 to 32,767 | Signed 16-bit integer | |
0 to 65,535 | Unsigned 16-bit integer | |
-2,147,483,648 to 2,147,483,647 | Signed 32-bit integer | |
0 to 4,294,967,295 | Unsigned 32-bit integer | |
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 | Signed 64-bit integer | |
0 to 18,446,744,073,709,551,615 | Unsigned 64-bit integer |
由上可以看出,integer类型的变量能够表示的最大值是由ulong类型的最大值决定的。
3)浮点类型数据
Type | Approximate range | Precision |
±1.5e−45 to ±3.4e38 | 7 digits | |
±5.0e−324 to ±1.7e308 | 15-16 digits |
4)默认值,C#是一个强类型的语言,不允许使用未初始化的变量。但是由1)中的表可以看出,简单数据类型中的有些是系统内的类型的简称,即如果用new操作符进行如下操作,变量就会有默认值了。(可以理解为new是操作对象的,一个new出一个对象后,在内存里面就为这个变量分配了一个存储区域)
int myInt = new int();<——>int myInt = 0
namespace TestType { class Program { static void Main(string[] args) { bool flag ; System.Console.WriteLine(flag); } } } |
运行后,系统报错“flag”未被初始化。
namespace TestType { class Program { static void Main(string[] args) { bool flag = new bool(); System.Console.WriteLine(flag); } } } |
运行后,打印出:flase
new操作符后,默认值如下:
Value type | Default value |
false | |
0 | |
'/0' | |
0.0M | |
0.0D | |
The value produced by the expression (E)0, where E is the enum identifier. | |
0.0F | |
0 | |
0L | |
0 | |
0 | |
The value produced by setting all value-type fields to their default values and all reference-type fields to null. | |
0 | |
0 | |
0 |