如何在每次新迭代中创建新实例 [英] How Do I Create New Instance Every New iteration
本文介绍了如何在每次新迭代中创建新实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想创建新实例每次新迭代我都试图连接对象名称而不是错误
I Want To Create New Instance Every New iteration And I Am My Trying To concatenate Object Name Than It Throws Error
static void Main(string[] args)
{
int i;
char ch = 'n';
while(ch=='n')
{
for(i=0;i<=10;i++)
{ // I Want To Create New Instance Every New iteration And My Trying To concatenate Object Name It Throws Error
lern "st"+i = new lern();
}
}
}
}
class lern
{
public static int i = 0;
public int m1,m2,m3;
public string nm, sub;
public lern ()
{
}
}
推荐答案
否,错误的方式。
在C#中不允许在运行时创建变量名,这意味着使用C#你的解决方案是不可能的。
您应该查看有关数组
的文档和可调整大小的列出
。
No, Wrong way.
In C# do not allow to create variables names at runtime, this mean that your solution is impossible with C#.
You should have a look at documentation aboutarrays
and resizeablelists
.
你不能创建这样的变量
You cannot create a variable like this
lern "st"+i = new lern();
c#中的
。它甚至不会编译。
你必须这样做:
in c#. It will not even compile.
You have to do something like this:
List<lern> lernList = new List<lern>();
for (i=0; i<=10; i++)
{
lernList.Add(new lern());
}
也就是说,我们必须看看你的外环。
That said, we have to take a look at your outer loop.
while (ch=='n')
{
...
}
你将如何摆脱这种循环?
你在哪里更改 ch
的值?
你不能这样做。您无法在运行时创建变量名称,因为编译器无法检查它们!即使你可以,你也不能使用它们,因为它们会在列表的末尾超出范围。
你想要做的就是使用数组或集合:
You can't do that. You can't create variable names at run time, because the compiler can't check them! Even if you could, you couldn;t use them as they would go "out of scope" at the end of the list.
What you want to do is use an array, or a collection:
private List<lern> lerns = new List<lern>();
static void Main(string[] args)
{
int i;
char ch = 'n';
while(ch=='n')
{
for(i=0;i<=10;i++)
{
lern l = new lern();
lerns.Add(l);
}
}
}
然后在后续代码中,您可以单独引用每个实例:
Then in subsequent code you can refer to each instance separately:
lern firstLern = lerns[0];
lern lastLern = lerns[lerns.Count - 1];
这篇关于如何在每次新迭代中创建新实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文