关于C#中结构体定义的问题,请教各位大哥,我是菜鸟!

在C++中这么定义的一个结构体,在C#上这么实现呢?
struct Mon_SendPack
{
unsigned command;
unsigned dspid;
unsigned address;
unsigned length;
unsigned data1;
unsigned data2;
unsigned data3;
unsigned bak[9];
char data[960];
};
我试了这样,不行;编译不通过
public struct Mon_SendPack
{
uint command;
uint dspid;
uint address;
uint length;
uint data1;
uint data2;
uint data3;
uint[] bak = new uint[9];
char[] data =new char[960];
}
我的问题说清楚了吧

定义的时候,数组不要初始化,不然编译通不过。
public struct Mon_SendPack
{
public uint command;
public uint dspid;
public uint address;
public uint length;
public uint data1;
public uint data2;
public uint data3;
public uint[] bak;
public char[] data;
}

使用的时候再初始化:
Mon_SendPack st = new Mon_SendPack();
st.bak = new uint[9];追问

哦,可是我要使用很多次,每次都new一下,不知道会不会影响效率啊。

追答

使用很多次不同的结构体实体吗?那必须得这样啊,得申请内存不是吗。
如果是同一个实体重用的话,只需要在最开始new一次就好了。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-04-28
楼主,在结构体里有几个概念你要弄清楚,定义的类型必须是值类型,而不是引用类型。还有结构体内是不允许赋初始值的,且也不允许设置数组的大小,因为设置大小等于与赋值,只是赋的是空值而已。
//在加载事件里给数组设置大小。
protected void Page_Load(object sender, EventArgs e)
{
Mon_SendPack.bak = new uint[9];
Mon_SendPack.data = new char[960];
}
public struct Mon_SendPack
{
uint command;
uint dspid;
uint address;
uint length;
uint data1;
uint data2;
uint data3;
public static uint[] bak;
public static char[] data;
}
第2个回答  2012-04-28
public struct Mon_SendPack
{
uint command;
uint dspid;
uint address;
uint length;
uint data1;
uint data2;
uint data3;
uint[] bak ;
char[] data;
public Mon_SendPack()
{
bak =new uint[9];
data=new char[960];
}
}
可以这样来初始化,不过看你的类名似乎是想在网络上发送这个结构体,这样写仍然有问题,因为C#的数组是在堆上分配的,结构体里只保存了一个对数组的引用.
必须要把结构体声明成可序列化的.追问

是准备通过网络发送,但是这样还是没编译通过。难道只有当使用的时候再new了吗?可是我有多次的使用这个结构体,那样岂不是很麻烦?

第3个回答  2012-04-29
public struct Mon_SendPack {

/// unsigned int
public uint command;

/// unsigned int
public uint dspid;

/// unsigned int
public uint address;

/// unsigned int
public uint length;

/// unsigned int
public uint data1;

/// unsigned int
public uint data2;

/// unsigned int
public uint data3;

/// unsigned int[9]
[System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst=9, ArraySubType=System.Runtime.InteropServices.UnmanagedType.U4)]
public uint[] bak;

/// char[960]
[System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.ByValTStr, SizeConst=960)]
public string data;
}
第4个回答  2012-04-28
结构中不能有实例字段初始值,也就是说最后那两个new出来的数组只能定义,不能实例化。
第5个回答  2012-05-03
struct 结构体类型名称
{
public 类型名称1 结构成员名称1;
public 类型名称2 结构成员名称2;
.........
}
例如
struct employe
{
public string name;
public bool sex;
public string phone;
publicdecimal pay;
}