对于整Socket网络通讯的人来说,packet这玩意一定不会陌生.但是要知道此类的字段字节总数,使用Marshal.SizeOf,无疑是一个非常好的选择.这样可以大大节省你计算字节数的时间.
使用方法:Marshal.SizeOf( packet实例 )
using System;
using System.Runtime.InteropServices;
using CMD.com;
namespace CMD
{
public class Program
{
static void Main(string[] args)
{
Myttee my = new Myttee();
my.bcc = 2;
Console.WriteLine(Marshal.SizeOf(my));
Console.Read();
}
}
}
关于 Myttee:
//=====================================================================
//
// All right reserved
// filename : Myttee
// description :
//
// create by User at 2016/8/11 13:48:31
//=====================================================================
using System.Runtime.InteropServices;
namespace CMD.com
{
[StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)]
internal struct Myttee
{
public ushort wcc;
public ushort bcc;
private ushort ccc;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
public char[] MachineID;
public void Init()
{
this.ccc = 10;
this.MachineID = new char[] {'1', '2', '3'};
}
public ushort MKK
{
get { return 1; }
}
}
}
其结果为26 . 3个ushort + 10个unicode字符 = 3X2 + 10X2 = 26
当然 : 如果没有 [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)] 特性
则使用Marshal.SizeOf就是一个坑 , 谁知道String占多少字节???
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。