2024年6月15日发(作者:)

C#中的int、long、float、double等类型都占多少个字节的内

存?

上测试代码

using System;

public static class Program

{

public static void Main(string[] args)

{

ine("{0}: {1} byte(s) scope:[{2}-{3}]",

typeof(byte).t(8), sizeof(byte).NumberPad(2),

Pad(32, true), Pad(32));

ine("{0}: {1} byte(s) scope:[{2}-{3}]",

typeof(sbyte).t(8), sizeof(sbyte).NumberPad(2),

Pad(32, true), Pad(32));

ine("{0}: {1} byte(s) scope:[{2}-{3}]",

typeof(short).t(8), sizeof(short).NumberPad(2),

Pad(32, true), Pad(32));

ine("{0}: {1} byte(s) scope:[{2}-{3}]",

typeof(ushort).t(8), sizeof(ushort).NumberPad(2),

Pad(32, true), Pad(32));

ine("{0}: {1} byte(s) scope:[{2}-{3}]",

typeof(int).t(8), sizeof(int).NumberPad(2),

Pad(32, true), Pad(32));

ine("{0}: {1} byte(s) scope:[{2}-{3}]",

typeof(uint).t(8), sizeof(uint).NumberPad(2),

Pad(32, true), Pad(32));

ine("{0}: {1} byte(s) scope:[{2}-{3}]",

typeof(long).t(8), sizeof(long).NumberPad(2),

Pad(32, true), Pad(32));

ine("{0}: {1} byte(s) scope:[{2}-{3}]",

typeof(ulong).t(8), sizeof(ulong).NumberPad(2),

Pad(32, true), Pad(32));

ine("{0}: {1} byte(s) scope:[{2}-{3}]",

typeof(float).t(8), sizeof(float).NumberPad(2),

Pad(32, true), Pad(32));

ine("{0}: {1} byte(s) scope:[{2}-{3}]",

typeof(double).t(8), sizeof(double).NumberPad(2),

Pad(32, true), Pad(32));

ine("{0}: {1} byte(s) scope:[{2}-{3}]",

typeof(decimal).t(8), sizeof(decimal).NumberPad(2),

Pad(32, true), Pad(32));

ine("{0}: {1} byte(s)",

typeof(bool).t(8), sizeof(bool).NumberPad(2));

ine("{0}: {1} byte(s)",

typeof(char).t(8), sizeof(char).NumberPad(2));

ine("{0}: {1} byte(s) ",

typeof(IntPtr).t(8), Pad(2));

ne();

}

public static string NumberPad(this T value, int length, bool right = false)

{

if (right)

{

return ng().PadRight(length);

}

else

{

return ng().PadLeft(length);

}

}

}

结果如下

Byte: 1 byte(s) scope:[0 - 255]

SByte: 1 byte(s) scope:[-128 - 127]

Int16: 2 byte(s) scope:[-32768 - 32767]

UInt16: 2 byte(s) scope:[0 - 65535]

Int32: 4 byte(s) scope:[-2147483648 - 2147483647]

UInt32: 4 byte(s) scope:[0 - 4294967295]

Int64: 8 byte(s) scope:[-9223372 - 9223372]

UInt64: 8 byte(s) scope:[0 - 18446744]

Single: 4 byte(s) scope:[-3.4028235E+38 - 3.4028235E+38]

Double: 8 byte(s) scope:[-1.7976931348623157E+308 - 1.7976931348623157E+308]

Decimal: 16 byte(s) scope:[-792287593543950335 - 792287593543950335]

Boolean: 1 byte(s)

Char: 2 byte(s)

IntPtr: 8 byte(s)

以上结果需要注意,在32位系统中,IntPtr为4字节,在64位系统中,IntPtr为8字节。