sizeof

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)]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值