What could cause an assignment to not work?

2019-07-17 20:59发布

I am working on a project in C#, and for some reason, when I try to assign a value to an enum variable, the assignment does not happen. I would copy my code, but it is really just a simple assignment. It's something like:

testVar = MyEnum.TYPE_OF_ENUM;

where testVar is of type MyEnum. When I step through this line using the VisualStudio debugger, I can see that the value of testVar does not change. What could possibly make an assignment fail like that?

EDIT:

Ok I will provide more context.

public enum MyEnum1
{
    ONE,
    TWO,
    THREE,
    FOUR,
    FIVE,
    SIX,
    SEVEN,
    EIGHT
}

public enum MyEnum2
{
    A,
    B,
    C,
    D,
    E,
    F
}

public void StateMachine(MyEnum1 state1)
{
    if(state2 == MyEnum2.A)
    {
        switch (state1)
        {
            case MyEnum1.ONE:
                state2 = MyEnum2.B;
                MyFunc(MyEnum2.B);
                break;
            default:
                break;
        }
    }
    else if (state2 == MyEnum2.B)
    {
        switch(state1)
        {
            case MyEnum1.ONE:
                state2 = MyEnum2.B;
                MyFunc(MyEnum2.B);
                break;
            case MyEnum1.THREE:
                state2 = MyEnum2.C;
                MyFunc(MyEnum2.C);
                break;
            default:
                break;                
        }
    }
    // Etcetera
}

The failure occurs on the state2 = whatever assignments. (state2 is a field, not a property)

3条回答
时光不老,我们不散
2楼-- · 2019-07-17 21:04

If your enum has multiple values with the same underlying value, it may appear to not change:

public enum MyEnum {
    One = 1,
    Two = 1,
}

Here, you'd only ever see One. Similarly, a flag enumeration like:

[Flags]
public enum MyEnum {
    One = 1,
    Two = 2,
    All = One | Two,
}

You'd never see All, just One | Two.

查看更多
Evening l夕情丶
3楼-- · 2019-07-17 21:09

One possibility is property with a broken setter:

class C
{ 
    private MyEnum foo = MyEnum.Something;
    public MyEnum Foo 
    {
        get { return foo; }
        set { }
    }

    void DoSomething()
    {
        Foo = MyEnum.SomethingElse; // does nothing
    }
}
查看更多
4楼-- · 2019-07-17 21:12

Is MyEnum.TYPE_OF_ENUM the first value in the enum, or is TYPE_OF_ENUM assigned to a integer value of 0?

A non-initialized enum will be set to 0, so it may already match.

Otherwise, it is much more likely that you have something else going on that you haven't noticed yet.

查看更多
登录 后发表回答