[英]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[,]
. 想象一下我在传递
bool[,]
函数。 This bool[,]
is named grid1
or grid2
, depending on the situation. 根据情况,此
bool[,]
名为grid1
或grid2
。
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
. 因此,尽管您传递了对数组的引用,但是该方法无法知道您是偶然使用了名为
grid1
的变量作为参数还是使用名为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 当您使用类似$$ var之类的东西时,PHP中会存在这种情况,其中$ var将容纳grid1并变成$ 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
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.