本文介绍了将类数组存储在C#中的列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个课程如下:
class EUInput { public EUInput() { RtID = 0 ; } public int RtID {获得; set ; } }我想在列表中存储具有不同RtID值的此类。我尝试如下:
静态 void Main( string [] args) { EUInput clsEUInput = new EUInput (); 列表< euinput> list = new List< euinput>(); for ( int i = 0 ; i < 5 ; i ++) { clsEUInput.RtID = i; list.Add(clsEUInput); } foreach (EUInput obj 列表) { Console.WriteLine(obj.RtID.ToString()); } Console.ReadLine(); }我得到的输出为 4 4 4 4 4 但是我需要一个outupt 0 1 2 3 4
解决方案这是像 Wes Aday 已经指出: // EUInput clsEUInput = new EUInput();
你必须在for-loop中创建新对象 b>每个新值:
静态 void Main( string [] args) { // EUInput clsEUInput = new EUInput(); EUInput clsEUInput; 列表< euinput> list = new List< euinput>(); for ( int i = 0 ; i < 5 ; i ++) { // 每次都需要创建新对象 clsEUInput = new EUInput(); clsEUInput.RtID = i; list.Add(clsEUInput); } foreach (EUInput obj 列表) { Console.WriteLine(obj.RtID.ToString()); } Console.ReadLine(); } < / euinput > < / euinput > ;
I have a class as below:
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:
static void Main(string[] args) { EUInput clsEUInput = new EUInput(); List<euinput> list = new List<euinput>(); 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(); }I am getting an output as 4 4 4 4 4 But I need an outupt as 0 1 2 3 4
解决方案 This is the error like Wes Aday already pointed: //EUInput clsEUInput = new EUInput();You have to create the new objects in the for-loop for each new value:
static void Main(string[] args) { //EUInput clsEUInput = new EUInput(); EUInput clsEUInput; List<euinput> list = new List<euinput>(); for (int i = 0; i < 5; i++) { // you need to create new object every time clsEUInput = new EUInput(); clsEUInput.RtID = i; list.Add(clsEUInput); } foreach (EUInput obj in list) { Console.WriteLine(obj.RtID.ToString()); } Console.ReadLine(); } </euinput></euinput>更多推荐
将类数组存储在C#中的列表中
发布评论