Domanda

I've started programming in C# to develop some console applications and I was wondering how I could make a certain number of variables with a different name in a more efficient way. For now I'm doing something like this:

for(int i=1; i<=x; i++)
    switch(i) {
        case 1:
            Player player1=new Player(i, x);
            break;
        case 2:
            Player player2=new Player(i, x);
            break;
        case 3:
            Player player3=new Player(i, x);
            break;
        case 4:
            Player player4=new Player(i, x);
            break;
        case 5:
            Player player5=new Player(i, x);
            break;
        case 6:
            Player player6=new Player(i, x);
            break;
    }

I'm just wondering whether there are more effecient ways to solve this and what those ways are.

È stato utile?

Soluzione

You'd be better off making an array:

var players = new Player[x];
for (int i = 0; i < x; i++)
{
    players[i] = new Player(i, x);
}

or use Linq:

var players = Enumerable.Range(0, x)
                        .Select(i => new Player(i, x))
                        .ToArray();

You can then reference the players you created with.

var player1 = players[0]; // Note: array indexes start at 0

Of course, you may not actually need to use arrays, specifically. Many other collection classes might suit your problem better.

Further reading:

Altri suggerimenti

You could make a List of players

var players = new List<Player>;

for (int i = 0; i < x; i++)
{
    players.add(new Player(i, x));
}

Then the memory would be distributed at runtime.

I prefer not to use array's because you have to know in advance what size they will be. With lists you can dynamically assign value's and It will only ever take up as much space in memory as the list is in its current state.

I don't program in C# but it seems you're creating local variables : they are valid only in your loop.

Name your variables outside of the loop, then create them inside of it. You will have to test if they exist to work with them.

Just for a trick:

partial class Player {
    public Player(int i, int x) {
        this.Ordinal=i;
    }

    public int Ordinal {
        get;
        set;
    }

    public static int Total {
        get;
        set;
    }

    public delegate Trick Trick(out Player x);

    public static Trick Create(out Player x) {
        x=new Player(++Player.Total, 0); // the second int doesn't matter
        return Create;
    }
}

partial class TestClass {
    public static void TestMethod() {
        Player mom, dad, brother, sister, me;
        Player.Create(out mom)(out dad)(out brother)(out sister)(out me);
    }
}

You might want to define another way to implement the Total once you have more than one series of Player.

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