将类数组存储在C#中的列表中

编程入门 行业动态 更新时间:2024-10-17 21:21:06
本文介绍了将类数组存储在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#中的列表中

本文发布于:2023-11-13 14:53:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1584631.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   列表中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!