Domanda

I tried creating an instance of the StreamReader class in my XNA game. However, it always prints

Invalid token 'using' in class struct or interface member declaration

Why? On top of the code, theres

using System.IO;

The class:

class Enemy : Character
{
    //Several booleans and stuff
    using(StreamReader reader = new StreamReader("file.txt"))
    {
    }
}
È stato utile?

Soluzione

Place the code inside a method, not at the class-level.

class Enemy : Character
{
    //Several booleans and stuff

    private void SomeMethod()
    {
        using(StreamReader reader = new StreamReader("file.txt"))
        {
        }
    }
}

You typically want to keep the StreamReader open only as long as you need it, then close it as soon as possible. Once you've got a handle on some external resource like a physical file on disk, you don't want to hang on to that forever. Get what you need and release it.

"Alright, thanks, but is there a reason It doesn't work outside of a method?"

Not really sure what it would mean if you could do it. When you hit the end of the using block, the instance is disposed of. So if you could do this at the class-level, would it dispose of the instance immediately and make it unusable in the class? Or magically know to dispose of it when the class was disposed?

If you wanted to define it at the class-level, then define it without the using statement and have your class implement the IDisposable interface. Then you could close / flush / dispose of the instance in your public void Dispose() method. But I'd really recommend creating a StreamReader only as you need it.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top