【问题标题】:C# How to save an enum type to each structure in a structure arrayC#如何将枚举类型保存到结构数组中的每个结构
【发布时间】:2018-07-18 23:15:55
【问题描述】:

我在以重复模式检查每种类型的结构时遇到问题。

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°输出:

值00 = 5,值01 = 10;

值00 = 4,值01 = 8;

值00 = 6,值01 = 3;

2°, 3°... 重复后的输出:

值00 = 4,值01 = 8;

值00 = 6,值01 = 3;

myStruct[0].Type.Type00.Value00 and myStruct[0].Type.Type00.Value01

传递的值保持不变。

但是在

myStruct[0].OptionType, the passed value of OptionType.Type00

对 OptionType.Type01 的更改;

为什么会这样?我们怎样才能让它保持和以前一样的值?

【问题讨论】:

  • internal Type02 Type01; 我看不到Type02 的声明。那是type0吗?
  • 我已经复制了你的代码,但我看不到 OptionType 的值发生了变化。您认为它在哪里发生了变化?
  • 更正,是内部Type01 Type01;
  • 您仍然没有在代码中显示您认为 OptionType 的值发生变化的位置。你是在问为什么后续的运行只有两次重复?
  • 它只有两个代表,因为不知何故, myStruct [0] .OptionType = OptionType.Type00 更改为 myStruct [0] .OptionType = OptionType.Type01 然后当循环重复时,它将是错误的.

标签: c# struct enums


【解决方案1】:

示例代码重复两次,因为您将 i 设置为 0,然后 for 循环将其递增为 1,因此数组中的第一个元素被跳过。如果它实际上改变了OptionType 的值,它仍然会打印一行,其中两个值都是 0。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-21
    • 2019-03-02
    • 1970-01-01
    • 2020-08-11
    • 2019-02-07
    相关资源
    最近更新 更多