【C#笔记】sizeof()

来源:互联网 发布:网络虚拟手机号 编辑:程序博客网 时间:2024/06/05 10:49

【C#笔记】sizeof()

今天写程序时要用到sizeof
在c里面可以直接调用函数sizeof()就行。
但是在c#中有些差异。

 

复制代码
 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 }
复制代码

 

 

从上面这个程序来看,
以类型定义关键字作为参数得到 类型大小时,
这样使用 sizeof(type); //type 指int double 等类型
以变量作为参数,得到变量所占空间大小时,
这样使用 System.Runtime.InteropServices.Marshal.sizeof(val); // val指一个变量名

0 0