如何在C#中将结构转换为字节数组?
我已经定义了这样的结构:
public struct CIFSPacket
{
public uint protocolIdentifier; //The value must be "0xFF+'SMB'".
public byte command;
public byte errorClass;
public byte reserved;
public ushort error;
public byte flags;
//Here there are 14 bytes of data which is used differently among different dialects.
//I do want the flags2. However, so I'll try parsing them.
public ushort flags2;
public ushort treeId;
public ushort processId;
public ushort userId;
public ushort multiplexId;
//Trans request
public byte wordCount;//Count of parameter words defining the data …Run Code Online (Sandbox Code Playgroud) I received some data (many times) which are encapsulated inside a struct. what I need to do is write them to a file (binary) to restore the data. how will you do it?
我可以struct直接序列化类型,因为它是一个值类型.
我已经在课堂上使用它,但想知道它是否可以单独使用结构.
例如
struct student
{
name string; --string is a reference type
age int;
designation string; --string is a reference type
salary double;
};
class foo
{
foo(){
student s;
s.name = "example";
serialize(s);
}
}
Run Code Online (Sandbox Code Playgroud)
这个链接说 "我试过让我的struct实现ISerializable,但我无法实现所需的构造函数,因为这是一个结构而不是一个对象."
我是C#的新手.
我试图理解为什么结构大小增长.
即:
struct Test
{
float x;
int y;
char z;
}
Run Code Online (Sandbox Code Playgroud)
Test结构的大小实际上是10个字节(float = 4,int = 4,char = 2).
但是,当我试图用Marshal.SizeOf(..)方法获得sizeof结构时,我得到了12.
在C++中我做pragma pack(1)了防止这个但是我怎么能在C#中做到这一点?
另一个问题:
当我试图将Test结构转换为字节数组时,如果结构不是[Serialize]我得到的字节数组大小为12字节为例外(或不是),但如果结构是[Serialize]我得到大小为170字节的字节数组,为什么会这样?
谢谢!:)