C# Marshal.SizeOf
对于整Socket网络通讯的人来说,packet这玩意一定不会陌生.但是要知道此类的字段字节总数,使用Marshal.SizeOf,无疑是一个非常好的选择.这样可以大大节省你计算字节数的时间.
使用方法:Marshal.SizeOf( packet实例 )
usingSystem;usingSystem.Runtime.InteropServices;usingCMD.com;namespaceCMD{publicclassProgram{staticvoidMain(string[]args){Mytteemy=newMyttee();my.bcc=2;Console.WriteLine(Marshal.SizeOf(my));Console.Read();}}}
关于 Myttee:
//=====================================================================////Allrightreserved//filename:Myttee//description:////createbyUserat2016/8/1113:48:31//=====================================================================usingSystem.Runtime.InteropServices;namespaceCMD.com{[StructLayout(LayoutKind.Sequential,Pack=1,CharSet=CharSet.Unicode)]internalstructMyttee{publicushortwcc;publicushortbcc;privateushortccc;[MarshalAs(UnmanagedType.ByValArray,SizeConst=10)]publicchar[]MachineID;publicvoidInit(){this.ccc=10;this.MachineID=newchar[]{'1','2','3'};}publicushortMKK{get{return1;}}}}
其结果为26 . 3个ushort + 10个unicode字符 = 3X2 + 10X2 = 26
当然 : 如果没有[MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)] 特性
则使用Marshal.SizeOf就是一个坑 , 谁知道String占多少字节???
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。