我有一个课程如下,
class EUInput
{
public EUInput()
{
RtID = 0;
}
public int RtID { get; set; }
}
我想在列表中存储具有不同RtID值的此类。我试过如下,
static void Main(string[] args)
{
EUInput clsEUInput = new EUInput();
List list = new List();
for (int i = 0; i < 5; i++)
{
clsEUInput.RtID = i;
list.Add(clsEUInput);
}
foreach (EUInput obj in list)
{
Console.WriteLine(obj.RtID.ToString());
}
Console.ReadLine();
}
我得到的输出为 4 4 4 4 4
但我需要一个outupt as 0 1 2 3 4
答案 0 :(得分:4)
您需要在 for循环中移动clsEUInput 的声明。现在,只有一个EUInput对象,并且您将多个相同的对象添加到列表中。
getPreferredSize()
答案 1 :(得分:1)
你需要班级的新实例 或者完整列表将包含对一个实例的引用
private class EUInput
{
public EUInput()
{
RtID = 0;
}
public int RtID { get; set; }
}
//I want to store this class with different RtID values in a list. I tried as below,
private static void Main(string[] args)
{
List<EUInput> list = new List<EUInput>();
for (int i = 0; i < 5; i++)
{
EUInput clsEUInput = new EUInput();
clsEUInput.RtID = i;
list.Add(clsEUInput);
}
foreach (EUInput obj in list)
{
Console.WriteLine(obj.RtID.ToString());
}
Console.ReadLine();
}
答案 2 :(得分:1)
将 {% extends "public/base.html" %}
{% block content %}
"Your code"
{% include "core/about.html" %}
{% endblock %}
更改为EUInput
(并按原样保留struct
方法):
Main
public struct EUInput
{
public int RtID;
}
是值类型(struct
是引用类型),因此当您将其添加到列表中时,您基本上会添加整个class
的“副本”尿素(而不仅仅是参考)。因此,当您不断更改循环中的struct
时,您仍然会更改您创建的那个对象,但列表中的对象不会受到影响。
要么你的老板在玩你一招,也就是想要测试你对价值类型和参考类型的了解,或者他不知道他们之间的区别......