列表中的C#对象正在互相覆盖

本文关键字:覆盖 对象 列表 | 更新日期: 2023-09-27 18:25:58

我正在查看的代码如下

string data;
string[] tokens;
while (sr.EndOfStream != true)
{
    data = sr.ReadLine();
    char delim = ',';
    tokens = data.Split(delim);
    Team t = new Team(tokens[0], int.Parse(tokens[1]), int.Parse(tokens[2]));
    TeamList.Add(t);
}
//Test to make sure the teams were stored properly
foreach(Team t in TeamList)
{
    Console.WriteLine(t.Name);
}
sr.Close();

当我使用foreach循环写出球队名称时,它会显示Team9的9份副本(球队在文本文件中逐行列出1-9,用逗号分隔的两个数字来表示每支球队的输赢,这就是为什么会用逗号来表示胜负)。这适用于我添加的任何数量的团队,如果我添加第10个团队,它会复制10个团队10,如果我使用8个团队,则会显示8个团队8。我在while循环中添加了foreach循环,让它显示每个阶段的团队,当它创建一个新对象时,它会覆盖所有以前的对象,所以例如,第一次运行循环时,它显示Team1,然后下次运行循环时显示Team2的两行,依此类推。从我的研究中,我发现这通常是由于没有在循环内声明新对象造成的,但是在这种情况下,在循环内部声明了一个新对象。

编辑:团队类如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
 namespace ConsoleApplication2
{
 class Team
{
    private static string tn;
    private static int Wins, Losses;
    public Team()
    {
    }
    public Team(string name, int wins, int losses)
    {
        tn = name;
        Wins = wins;
        Losses = losses;
    }
    public override string ToString()
    {
        return tn + ", wins: " + Wins + ", losses: " + Losses;
    }
    public string Name
    {
        get { return tn; }
    }
 }
}

TeamList变量和主类如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApplication2
{
 class Program
 {

    private static Random pick = new Random();
    private static List<Team> TeamList = new List<Team>();
    static void Main(string[] args)
    {      
        //Reading file io 
        Schedule(TeamList);
        Console.ReadLine();
    }
static void Schedule(List<Team> TeamList)
    {
        StreamReader sr = new StreamReader("C:/Users/andre/Desktop/VisualStudioProjects/ConsoleApplication1/ConsoleApplication1/TeamList.txt");
        string data;
        string[] tokens;
        while (sr.EndOfStream != true)
        {
            data = sr.ReadLine();
            char delim = ',';
            tokens = data.Split(delim);
            Team t = new Team(tokens[0], int.Parse(tokens[1]), int.Parse(tokens[2]));
            TeamList.Add(t);
            foreach(Team x in TeamList)
        {
                Console.WriteLine(x.Name);
            }
        }

        //Test to make sure the teams were stored properly
        foreach(Team t in TeamList)
        {
            Console.WriteLine(t.Name);
        }
        sr.Close();
      }

文本文件只是一个包含以下的文件

Team1,0,0
Team2,0,0
Team3,0,0
Team4,0,0
Team5,0,0
Team6,0,0
Team7,0,0
Team8,0,0
Team9,0,0

列表中的C#对象正在互相覆盖

您有

class Team
{
    private static string tn; //STATIC??
    private static int Wins, Losses; //STATIC??
}

static表示变量在应用程序中Team的所有实例之间共享。请把它取下来。这就是问题所在。