【C#笔记】sizeof()

【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指一个变量名
由于时间关系,就写了一个int类型的测试,其他类型的以后用到的时候再测试一下吧。

2009-12-26 11:46:50

原文地址:https://www.cnblogs.com/stublue/p/1661219.html