如何在运行时创建一系列编号变量?
朋友们,我必须创建一系列 ArrayList
,每个都包含来源未知的对象,每个实例都分配给一个单独的局部变量。
到目前为止,一切都很好......但我还需要每个局部变量的名称遵循非常特定的模式:名称应以“oArr”开头,后跟一个或多个数字,反映该特定数组在序列中的位置。此外,我在编译时不知道需要多少个数组,因此也不知道需要多少个局部变量!
我突然想到,这也许是一个可以通过 C# 4.0 中动态类型的可用性来解决的问题,但我对它们的使用一点也不熟悉。我如何获取这样的代码...
int i=0;
foreach(something)
{
ArrayList oArr+i=new ArrayList();
i++;
}
...并将其转换为符合上面列出的标准和实际编译的内容?
或者,是否有更简单、更理智的方法来解决这个问题?
Friends, I must create a series of ArrayList
s, each containing objects of unknown origin, with each instance assigned to a separate local variable.
So far, so good... But I also need each local variable's name to follow a very specific pattern: the name should begin with "oArr", followed by one or more digits reflecting that particular array's position within the sequence. Furthermore, I will not know at compile-time how many of these arrays - and hence, how many local variables - I will be needing!
It strikes me that this is perhaps a problem that could be solved by the availability of dynamic types in C# 4.0, however I am not at all familiar with their use. How might I take code like this...
int i=0;
foreach(something)
{
ArrayList oArr+i=new ArrayList();
i++;
}
...and turn it into something that matches the criteria outlined above and actually compiles?
Alternately, is there a more simple, sane approach to this problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您无法在执行期间更改变量的名称,因为代码(甚至 C# 代码)是使用特定的变量名称进行编译的。如果您可以在执行期间更改名称,则会导致问题。
例如,如果语言允许更改变量名称,那么当您尝试访问名为“var1”的变量时,编译器不知道在执行过程中该变量名称是否发生更改,现在称为“x”。
您可以尝试做的事情是允许您的程序动态编译一些代码,但这可能不是解决您问题的正确方法。如果您更好地解释您的需求,那么我们可以为您提供有效的解决方案。
希望这有助于
编辑:查看您的版本我可以告诉您,您当前使用的方法是不可能的。我可以建议你以下几点:
如果你需要的是让每个 ArrayList 有一个特定的名称,你可以记得你可以使用字典:
You cannot change the name of a variable during execution, since the code (even c# code) was compiled with a certain variable name. If you could change the name during execution then it would cause problems.
For example, if the language allowed to change variable names then when you try to access a variable named 'var1' the compiler has no idea if during execution that variable name changed and now is called 'x'.
Something you could try to do is to allow your program to dynamically compile some code but this is probably not the right solution to your problem. If you explain better what you need then we could provide you with an effective solution.
Hope this helped
EDIT: Seeing your editions I can tell you that it is impossible with the approach you are currently using. I could suggest you the following:
If what you need is to have each ArrayList to have a specific name you can recall you can use a dictionary:
这对你有用吗?
然后您可以通过索引访问每个数组列表。
Would this work for you?
Then you can access each array list by index.
使用 ArrayList 的列表。
Use a List of ArrayLists.