class Program19 { static void Main(string[] args) { // true,或false Console.WriteLine("bool占用:" + sizeof(bool)); //0-255 Console.WriteLine("byte 占用:"+sizeof(byte)); //-128 到 127 Console.WriteLine("sbyte 占用:" + sizeof(sbyte)); Console.WriteLine("char 占用:" + sizeof(char)); //-79228162514264337593543950335 到 + 79228162514264337593543950335 Console.WriteLine("decimal 占用:" + sizeof(decimal)); //±5.0 × 10−324 到 ±1.7 × 10308 15-16 位 Console.WriteLine("double 占用:" + sizeof(double)); //±1.5 x 10−45 至 ±3.4 x 1038 7位 Console.WriteLine("float 占用:" + sizeof(float)); //-2,147,483,648 到 2,147,483,647 带符号的 32 位整数 Console.WriteLine("int 占用:" + sizeof(int)); //0 到 4,294,967,295 无符号的 32 位整数 Console.WriteLine("uint 占用:" + sizeof(uint)); //-9,223,372,036,854,775,808 到 9,223,372,036,854,775,807 64 位带符号整数 Console.WriteLine("long 占用:" + sizeof(long)); //0 到 18,446,744,073,709,551,615 无符号 64 位整数 Console.WriteLine("ulong 占用:" + sizeof(ulong)); //-32,768 到 32,767 有符号 16 位整数 Console.WriteLine("short 占用:" + sizeof(short)); //0 到 65,535 无符号 16 位整数 Console.WriteLine("ushort 占用:" + sizeof(ushort)); byte[] bytes = Encoding.UTF8.GetBytes("我们"); Console.WriteLine(Encoding.GetEncoding("gb2312").GetBytes("我们").Length); Console.WriteLine(bytes.Length); Console.ReadLine(); } }
string占用的字节数和编码有关系,如果是UTF8则每个汉字占用3个字节,如果是gb2312则占用2个字节
2、而在实际的运行中,到底分配多少字节是和编译器有关系,来看一下c#生成好的EXE文件的IL代码:
static void Main() { int a8 = 8; int a = 32; Int16 a16 = 32767; Int32 a32 = 2147483647; Int64 a64 = 9223372036854775807; Int64 aa64 = 8; Int64 aaa64 = 32; Console.WriteLine(a); Console.WriteLine(a8); Console.WriteLine(a16); Console.WriteLine(a32); Console.WriteLine(a64); }
看一下IL代码:
.method private hidebysig static void Main() cil managed { .entrypoint // Code size 75 (0x4b) .maxstack 1 .locals init ([0] int32 a8, [1] int32 a, [2] int16 a16, [3] int32 a32, [4] int64 a64, [5] int64 aa64, [6] int64 aaa64) IL_0000: nop IL_0001: ldc.i4.8 IL_0002: stloc.0 IL_0003: ldc.i4.s 32 IL_0005: stloc.1 IL_0006: ldc.i4 0x7fff IL_000b: stloc.2 IL_000c: ldc.i4 0x7fffffff IL_0011: stloc.3 IL_0012: ldc.i8 0x7fffffffffffffff IL_001b: stloc.s a64 IL_001d: ldc.i4.8 IL_001e: conv.i8 IL_001f: stloc.s aa64 IL_0021: ldc.i4.s 32 IL_0023: conv.i8 IL_0024: stloc.s aaa64 IL_0026: ldloc.1 IL_0027: call void [mscorlib]System.Console::WriteLine(int32) IL_002c: nop IL_002d: ldloc.0 IL_002e: call void [mscorlib]System.Console::WriteLine(int32) IL_0033: nop IL_0034: ldloc.2 IL_0035: call void [mscorlib]System.Console::WriteLine(int32) IL_003a: nop IL_003b: ldloc.3 IL_003c: call void [mscorlib]System.Console::WriteLine(int32) IL_0041: nop IL_0042: ldloc.s a64 IL_0044: call void [mscorlib]System.Console::WriteLine(int64) IL_0049: nop IL_004a: ret } // end of method Program2::Main
可以看到,同样定义的是Int64的类型,1个是8,1个是32,1个是9223372036854775807
前两个都是4个字节:ldc.i4.8 ldc.i4.s
而后一个就是8个字节:ldc.i8