对于整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占多少字节???
本文出自 “Better_Power_Wisdom” 博客,请务必保留此出处http://aonaufly.blog.51cto.com/3554853/1836862
原文:http://aonaufly.blog.51cto.com/3554853/1836862