用两级数组c#填充复杂结构
本文关键字:填充 复杂 结构 数组 两级 | 更新日期: 2023-09-27 18:29:00
我想为用C#编写的结构设置值,但我得到了一个错误。
private struct pack2
{
public float var;
public float [3]var2;
}
private struct pack
{
public pack2[] ster;
}
private void recv()
{
pack mystruct;
mystruct.ster = new pack2[4]; // Because I need to declare 4 structures of pack2
mystruct.ster[0].var = 2F;
mystruct.ster[0].var[0] = 1F; // error
}
错误:NullReferenceException未处理,Addinfo:对象引用未设置为对象的实例
我该怎么修?
已解决:
private struct pack2
{
public float var;
public float [3]var2;
}
private struct pack
{
public pack2[] ster;
}
private void recv()
{
pack mystruct;
mystruct.ster = new pack2[4]; // Because I need to declare 4 structures of pack2
mystruct.ster[0].var = 2F;
mystruct.ster[0].var2 = new float[3]; // Because I need 3 floats on each pack2
mystruct.ster[1].var2 = new float[3]; // Because I need 3 floats on each pack2
mystruct.ster[2].var2 = new float[3]; // Because I need 3 floats on each pack2
mystruct.ster[3].var2 = new float[3]; // Because I need 3 floats on each pack2
mystruct.ster[0].var2[0] = 1F;
mystruct.ster[0].var2[1] = 1F;
mystruct.ster[0].var2[2] = 1F;
}
我希望对人们有用。感谢alex
您需要初始化数组。
// One instance
ster = new pack2[1];
您可以在此处找到有关阵列的更多信息。
结构在实际代码中很少有用。大多数时候你应该使用类。
关于何时使用structs(很少),请参阅以下答案。