C#中sizeof用法

转载自:http://www.cnblogs.com/stublue/archive/2010/02/01/1661219.html

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. namespace test  
  6. {  
  7.     class Program  
  8.     {  
  9.         static void Main(string[] args)  
  10.         {  
  11.             int val = 8;  
  12.             //Console.WriteLine(sizeof(val)); //这个会报错。  
  13.             Console.WriteLine(sizeof(int)); //这个正常,跟c里的一样  
  14.   
  15.             Console.WriteLine(System.Runtime.InteropServices.Marshal.SizeOf(val)); //这个能正常输出,查文档得到。  
  16.             //Console.WriteLine(System.Runtime.InteropServices.Marshal.SizeOf(int));//这个会报错。  
  17.             Console.ReadKey();  
  18.         }  
  19.     }  
  20. }  
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            int val = 8;
            //Console.WriteLine(sizeof(val)); //这个会报错。
            Console.WriteLine(sizeof(int)); //这个正常,跟c里的一样

            Console.WriteLine(System.Runtime.InteropServices.Marshal.SizeOf(val)); //这个能正常输出,查文档得到。
            //Console.WriteLine(System.Runtime.InteropServices.Marshal.SizeOf(int));//这个会报错。
            Console.ReadKey();
        }
    }
}


  1. 从上面这个程序来看,  
  2. 以类型定义关键字作为参数得到 类型大小时,  
  3. 这样使用 sizeof(type); //type 指int double 等类型  
  4. 以变量作为参数,得到变量所占空间大小时,  
  5. 这样使用 System.Runtime.InteropServices.Marshal.sizeof(val); // val指一个变量名  
  6. 由于时间关系,就写了一个int类型的测试,其他类型的以后用到的时候再测试一下吧。  
从上面这个程序来看,
以类型定义关键字作为参数得到 类型大小时,
这样使用 sizeof(type); //type 指int double 等类型
以变量作为参数,得到变量所占空间大小时,
这样使用 System.Runtime.InteropServices.Marshal.sizeof(val); // val指一个变量名
由于时间关系,就写了一个int类型的测试,其他类型的以后用到的时候再测试一下吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值