简体   繁体   中英

Dynamic variable names in C#?

(There's not an actual function where I need this, but I was just wondering.)

Imagine this function where I pass a bool[,] . This bool[,] is named grid1 or grid2 , depending on the situation.

I was wondering if I can do anything like the following:

void CheckGrid(bool[,] grid, int number)
{
    for (int x = 0; x <= gridXmax - 1; x++)
    {
        for (int y = 0; y <= gridYmax - 1; y++)
        {
            if(grid + number[x,y]) //this will check against grid1 or grid2, depending on int number
                //logic depends on whether it's grid1 or grid2
        }
    }
}

Guessing by the questions for other languages, it probably isn't possible. But you never know :)

It is well possible I'm missing something obvious here - I'm not really experienced.

You can create an array of grids, then use the number value to check that.

List<bool[,] grids = new List<bool[,]>();

then

if (grids[number][x,y])...

No - an object doesn't have a name, only a variable has a name. So although you pass a reference to an array, there's no way that the method can know whether you happened to use a variable called grid1 for the argument or a variable called grid2 .

Usually when there are questions like this, the answer involves saying that you can use reflection to access member variables by name, but it's generally a bad idea to do so - and that using a single variable which is a collection is a better idea. However, in your question it's pretty unclear what you're trying to do anyway... if it is trying to determine "the name of the object" then that's definitely infeasible in general.

最好将一个标志传递给函数,这将使您可以根据要处理的是grid1还是grid2来更新逻辑。

This kind of thing exists in PHP when you use something like this $$var where $var will hold grid1 and turn into $grid1

The only thing I could suggest was using key / value pairs in a dictionary and concatenating the number to 'grid'

Add a dimension to your array.

void CheckGrid(bool[,,] grid, int number)
{
    for (int x = 0; x <= gridXmax - 1; x++)
    {
        for (int y = 0; y <= gridYmax - 1; y++)
        {
            if(grid[number, x,y]) //this will check against grid1 or grid2, depending on int number
                //logic depends on whether it's grid1 or grid2
        }
    }
}  

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