sizeof() 是C#中的运算符,用于获取编译时已知类型的字节大小,不适用于变量或实例。
语法:
int sizeof(type);
它接受类型并返回一个int值-该类型的大小以字节为单位。
示例
sizeof(char) - 2 sizeof(int) - 4 sizeof(long) - 8
看下面的代码-显示不同类型的大小。
using System; using System.Text; namespace Test { class Program { static void Main(string[] args) { Console.WriteLine("size of {0} is {1} bytes", typeof(bool), sizeof(bool)); Console.WriteLine("size of {0} is {1} bytes", typeof(byte), sizeof(byte)); Console.WriteLine("size of {0} is {1} bytes", typeof(char), sizeof(char)); Console.WriteLine("size of {0} is {1} bytes", typeof(UInt32), sizeof(UInt32)); Console.WriteLine("size of {0} is {1} bytes", typeof(ulong), sizeof(ulong)); Console.WriteLine("size of {0} is {1} bytes", typeof(decimal), sizeof(decimal)); //按ENTER退出 Console.ReadLine(); } } }
输出结果
size ofSystem.Booleanis 1 bytes size ofSystem.Byteis 1 bytes size ofSystem.Charis 2 bytes size of System.UInt32 is 4 bytes size of System.UInt64 is 8 bytes size ofSystem.Decimalis 16 bytes