C#:如何在for循环中为整数(i)分配许多变量? [英] C#: How do i assign many variables with an integer(i) in for loop?

查看:373
本文介绍了C#:如何在for循环中为整数(i)分配许多变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下,我们有5个字符串变量,我们希望在运行时为它们分配Foo。

Imagine we have 5 string variables and we want to assign "Foo" to them during runtime.

而不是这个

string a1 = "Foo";
string a2 = "Foo";
string a3 = "Foo";
string a4 = "Foo";
string a5 = "Foo";

我们不能使用这样的东西:

Can't we use something like this:

for(int i = 0;i < 5;i++)
{
    a+i = "Foo";
}

是否无法以类似的方式访问它们?

Is it impossible to access them in a similiar way?

推荐答案

正如其他人所说,数组(或其他集合)是一种更好的方法。

As others have said, an array (or another collection) is a much better way of doing this.

将数组视为仅通过索引始终访问的变量集合。

Think of an array as just being a collection of variables which you always access by index.

我不能想一想为什么你想要有一组变量,如你的问题所示。如果你绝对这样做,并且它们是实例/静态变量,你可以使用反射来访问它们,如果你真的想要 - 但是使用数组或其他集合会更好,更好。

I can't think of any reason why you'd want to have a set of variables as shown in your question. If you absolutely have to do that, and they're instance/static variables, you could use reflection to access them if you really wanted to - but using an array or other collection would be much, much better.

这篇关于C#:如何在for循环中为整数(i)分配许多变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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