The sizeof operator is used to obtain the size in bytes for a value type. A sizeof expression takes the form:
sizeof(type)
where:
-
type
- The value type for which the size is obtained.
Remarks
The sizeof operator can be applied only to value types, not reference types.
The sizeof operator can only be used in the unsafe mode.
The sizeof operator cannot be overloaded.
Example
// cs_operator_sizeof.cs // compile with: /unsafe // Using the sizeof operator using System; class SizeClass { // Notice the unsafe declaration of the method: unsafe public static void SizesOf() { Console.WriteLine("The size of short is {0}.", sizeof(short)); Console.WriteLine("The size of int is {0}.", sizeof(int)); Console.WriteLine("The size of long is {0}.", sizeof(long)); } } class MainClass { public static void Main() { SizeClass.SizesOf(); } }
Output
The size of short is 2. The size of int is 4. The size of long is 8.
sizeof 只可以用与value type
reference type 大小呢?
struct Struct1 { }
struct Struct2 { long l;}
struct Struct3 { byte b;}
struct Struct4 { long l; byte b;}
unsafe static void Main(string[] args)
{
Console.WriteLine(sizeof(Struct1) + "、" + sizeof(Struct2) + "、" + sizeof(Struct3) + "、" + sizeof(Struct4));
Console.ReadLine();
}
结果是:1、8、1、16
Struct1是空的,sizeof(Struct1)为什么不是0?
如果struct本身占1字节那么Struct2为什么不是1+8=9?
如果如Struct2、Struct3所示,struct占用字节数只取决于其中的字段,为什么Struct4不是8+1=9?
给结构加上这个属性就行了:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]