简体   繁体   中英

C# gets an enum, but doesn't work correctly with switch statement

Im having some trouble with enums and then checking it with a switch statement. I'm not sure if I'm doing something super wrong, but I don't get any errors so hey.

# Level.cs

enum LevelID
{
    Level_One = 0,
    Level_Two = 1,
}

private LevelID lvlID;
private string xml;

StreamReader xmlStream;

public Level()
{
    switch (lvlID)
    {
        case LevelID.Level_One:
            xmlStream = new StreamReader("../../assets/xml/test1.tmx");
            break;
        case LevelID.Level_Two:
            xmlStream = new StreamReader("../../assets/xml/test2.tmx");
            break;
      }

      xml = xmlStream.ReadToEnd();
      xmlStream.Close();
}

public LevelID LvlID
{
    get { return this.lvlID; }
    set { this.lvlID = value; }
}

public string Xml
{
    get { return this.xml; }
}


## The xml gives me lots of numbers from the different files

# game.cs

Level lvl = new Level();
lvl.LvlID = LevelID.Level_Two;

## When I then get the lvlID from Level.cs again its says it holds Level_Two,
## but the switch still gives me the numbers from test1.xml

The thing is that I'm checking with an enum in a switch statement to determine what xml file I should store in a String that I parse into an XElement.

When I try to do this it always gives me the xml from the first switch case, even though that when I check, my enum variable holds the correct enum for the second case. Even without a default in my switch it still loads the first case's xml file. What is going on and what am I doing wrong?

So your switch is in the constructor. It's only evaluated when you instantiate the class. Since you're setting the property after that happens, the switch never sees it.

That said, this is something that could be trivially seen if you used your debugger. You could stop the code at the switch statement and see what the value was. Then you could step through the code to see why the value was not what you expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM