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

时间:2015-12-07 04:28:58

标签: c#

我正在查看的代码如下

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循环编写团队名称时,它会显示9个Team9副本(团队在文本文件中逐行列出1-9,两个数字用逗号分隔,以保存胜负每个团队,这就是用逗号区分的原因)。这适用于我添加的任意数量的团队,如果我添加第10个团队,它会执行10个团队10,如果我使用8个团队,则会显示8个团队的Team8。我将foreach循环添加到while循环中,让它在每个阶段显示团队,并在创建新对象时保持覆盖所有先前的对象,例如,第一次运行循环时它显示Team1,然后下一次它运行循环它显示两行Team2,依此类推。根据我的研究,我发现这通常是由于未在循环内声明一个新对象引起的,但在这种情况下,在循环内声明了一个新对象。

编辑:Team类如下

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

1 个答案:

答案 0 :(得分:2)

你有

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

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