在C#中生成变量 [英] Generate Variables in C#

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

问题描述

大家好
我想使用for循环或其他技术来生成数字变量.例如
我想生成5个变量以保存int值而不使用数组或列表或任何存储位置
我猜这个解决方案,我知道它不起作用:

Hello everyone
i want to Generate number Variable with for loop or another technique. for example
i want to Generate 5 variable to Save int Values without to use Array or list or any Storage locations
and i guess this solution and i know it''s not working :

for(int i = 0; i < 5; i++)
{
    Console.Write(" ID {0} : ",i+1);
    int ID = Convert.ToInt32(Console.ReadLine()); // ???? i don't want to override ID and i want to generate different ID to save different Values 
}

推荐答案

因此使用数组:

So use an array:

int[] ids = new int[5];

for(int i = 0; i < 5; i++)
{
    Console.Write(" ID {0} : ",i+1);
    ids[i] = Convert.ToInt32(Console.ReadLine());
}


您需要的称为数组.它是您可以创建的最简单的变量集合:
What you need is called an Array. It is the simplest collection of variables you can create:
int[] IDs = new int[5];
for (int i = 0; i < IDs.Length; i++)
   {
   Console.Write("ID {0} : ", i + 1);
   IDs[i] = Convert.ToInt32(Console.ReadLine());
   } 


请参阅我对该问题的评论,这可能是基于一些误解.您可能可以从此评论中了解它.考虑一下:

Please see my comment to the question, which is probably based on some misconception. Probably you will be able to understand it from this comment. Consider this:

int length = //...
int[] ids = new int[length];

for (int index = 0; index < length; ++index) {
    Console.Write(" ID {0}: ", index + 1);
    ids[index] = int.Parse(Console.ReadLine());
}



数组只是使对象(在这种情况下为整数类型)创建,可以访问,操作但没有单独名称(如变量)的一种方式.对象不必具有单独的名称,并且在许多情况下不能具有它们.其他情况包括集合,通过托管指针(引用)链接的任意对象图,其中链接表或树是此类图的简单示例.

—SA



Array is just one way of having the objects (of the integer type, in this case) which are created, can be accessed, manipulated, but have no individual names, such as variables. Objects do not have to have individual names, and, in many cases, cannot have them. Other cases include collections, arbitrary object graphs linked by managed pointers (references), with linked lists or trees being simple example of such graphs.

—SA


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

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