在重复模式下检查每种类型的结构时遇到问题。
private static MyStruct myStruct;
public Form1()
{
InitializeComponent();
myStruct = new MyStruct[3]
myStruct[0].OptionType = OptionType.Type00;
myStruct[0].Type.Type00.Value00 = 5;
myStruct[0].Type.Type00.Value01 = 10;
myStruct[1].OptionType = OptionType.Type01;
myStruct[1].Type.Type01.Value00 = 4;
myStruct[1].Type.Type01.Value01 = 8;
myStruct[2].Type.OptionType = OptionType.Type01;
myStruct[2].Type.Type01.Value00 = 6;
myStruct[2].Type.Type01.Value01 = 3;
}
private void btnClick_Click(object sender, EventArgs e)
{
for (int i = 0; i < myStruct.Length; i++)
{
switch (myStruct[i].OptionType)
{
case OptionType.Type00:
Console.WriteLine($"Value00 = {myStruct[i].Type.Type00.Value00} Value01 = {myStruct[i].Type.Type00.Value01}");
break;
case OptionType.Type01:
Console.WriteLine($"Value00 = {myStruct[i].Type.Type01.Value00} Value01 = {myStruct[i].Type.Type01.Value01}");
break;
}
//error
//if (i == 2)
//i = 0; //Repeat.
//solution
if (i == 2)
i = -1; //Repeat.
}
}
[StructLayout(LayoutKind.Sequential)]
public struct MyStruct
{
internal OptionType OptionType;
internal Type Type;
}
[StructLayout(LayoutKind.Explicit)]
internal struct Type
{
[FieldOffset(0)]
internal Type00 Type00;
[FieldOffset(0)]
internal Type01 Type01;
}
[Flags]
internal enum OptionType : uint
{
Type00 = 0,
Type01 = 1,
}
[StructLayout(LayoutKind.Sequential)]
internal struct Type00
{
internal int Value00;
internal int Value01;
}
[StructLayout(LayoutKind.Sequential)]
internal struct Type01
{
internal int Value00;
internal int Value01;
}
1°输出:
Value00 = 5,Value01 = 10;
Value00 = 4,Value01 = 8;
Value00 = 6,Value01 = 3;
2°,3°...重复输出:
Value00 = 4,Value01 = 8;
Value00 = 6,Value01 = 3;
在
myStruct[0].Type.Type00.Value00 and myStruct[0].Type.Type00.Value01
传递的值保持不变。
但是在
myStruct[0].OptionType, the passed value of OptionType.Type00
更改为OptionType.Type01;
为什么会发生?我们如何使其保持与以前相同的价值?
答案 0 :(得分:0)
该示例代码重复两次,因为您将i
设置为0,然后通过for循环将其递增为1,因此跳过了数组中的第一个元素。如果它实际上是在更改OptionType
的值,它仍会打印一行,只是两个值均为0。