在变量中使用变量? [英] Use a variable within a variable?

查看:111
本文介绍了在变量中使用变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个字段,每个字段都是这样的:

I have several fields, each one is like this:

field1
field2
field3
...

使用带计数器的循环,我希望能够说fieldx 。其中x是该循环中计数器的值。这意味着如果我的数组中有6个条目,则字段1 - 字段6将被赋予值。

Using a loop with a counter, I want to be able to say fieldx. Where x is the value of the counter in that loop. This means if I have 6 entries in my array, fields1 - field6 will be given values.

是否可以使用fieldx?

Is fieldx possible?

推荐答案

你可以用反射,但一般情况下,如果可以在数组中声明字段会更好。而不是:

You can do it with reflection, but in general it is better if you can declare your fields in an array. Instead of:

SomeType field1;
SomeType field2;
SomeType field3;
...
SomeType field6;

你可以这样做:

SomeType[] fields = new SomeType[6];

然后你可以循环设置值的数组:

Then you can loop over the array setting the values:

for (int i = 0; i < fields.length; ++i)
{
    fields[i] = yourValues[i];
}

这篇关于在变量中使用变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆