使用streamreader时无法将字符串转换为int

时间:2013-11-21 11:30:09

标签: c# string parsing int

我在将字符串转换为int时遇到问题。我环顾四周,被告知使用int.Parse,但它没有帮助。

我创建了一个Winnerint WinnerScore的对象string WinnerName。 我想在排序之前将这些值添加到数组Winner[]

当我运行此代码时,它说:

  

NullReferenceException未处理

     

对象引用未设置为对象的实例。

知道为什么会这样吗?

StreamReader sr = new StreamReader("highscores.txt");

for (int u = 0; u < nWinners; u++)
{
    unsortedList[u].WinnerScore = int.Parse(sr.ReadLine()); 
    unsortedList[u].WinnerName = sr.ReadLine(); 
}
sr.Close();

3 个答案:

答案 0 :(得分:1)

有了一定的信心,我可以假设您已经声明了数组unsortedList,但是您还没有初始化要存储在该数组中的Winner类的对象。

简单地声明

 Winner[] unsortedList = new Winner[100];

创建一个可以存储100个Winner实例的数组,但是这个数组是空的,在100个可用的插槽中没有Winner类的实例,它们都是null。您应该创建要存储在阵列的100个插槽中的每个Winner实例。

因此,作为示例,您的代码可以重写为

Winner[] unsortedList = new Winner[nWinners];
using(StreamReader sr = new StreamReader("highscores.txt"))
{
    for (int u = 0; u < nWinners; u++)
    {
        Winner w = new Winner();
        w.WinnerScore = int.Parse(sr.ReadLine()); 
        w.WinnerName = sr.ReadLine(); 
        unsortedList[u] = w;
    }
    sr.Close();
}

然而,这有一个缺点,在进入循环之前,您需要知道维护数组所需的Winner对象的确切数量。如果由于某种原因,您无法正确计算它们,则会遇到另一个问题(指数超出范围)。

在这种情况下,最好使用List<Winner>,在此之前您不需要知道元素的确切数量

List<Winner> unsortedList = new List<Winner>();
using(StreamReader sr = new StreamReader("highscores.txt"))
{
    while((line = sr.ReadLine()) != null))
    {
        Winner w = new Winner();
        w.WinnerScore = int.Parse(line); 
        w.WinnerName = sr.ReadLine(); 
        unsortedList.Add(w);
    }
    sr.Close();
}

答案 1 :(得分:0)

var unsortedList = new List<Winner>();

var nWinners = 100;
using (StreamReader sr = new StreamReader("highscores.txt"))
{
    for (int i = 0; i < nWinners; i++)
    {
        var winer = new Winner();
        winer.WinnerScore = int.Parse(sr.ReadLine());
        winer.WinnerName = sr.ReadLine();
        unsortedList.Add(winer);
    }
    sr.Close();
}

答案 2 :(得分:0)

你已经离开了创作和初始化:

// My suggestion of unsortedList generic type
public struct Winner {
  public int WinnerScore;
  public String WinnerName; 
}

...

// 1. You shoud create unsortedList:
List<Winner> unsortedList = new List<Winner>(); 

// 2. You should also initialize the list with Winner instances
for (int u = 0; u < nWinners; ++u)
  unsortedList.Add(new Winner());

// 3. Only that you can fill unsortedList from file.
//    And you original code becames the correct one
using (StreamReader sr = new StreamReader("highscores.txt")) {
  for (int u = 0; u < nWinners; ++u) {
    unsortedList[u].WinnerScore = int.Parse(sr.ReadLine()); 
    unsortedList[u].WinnerName = sr.ReadLine(); 
  } 
}