【发布时间】:2014-11-07 02:02:37
【问题描述】:
我有以下代码读取文本文件并在其中搜索整数。我正在使用“int.TryParse”来执行此操作,但它在运行后并未将整数值存储在列表中,只是想知道您能否告诉我这段代码有什么问题。谢谢。
namespace AccessErrorFile
{
class Program
{
static void Main(string[] args)
{
List<int> plans = new List<int>();
List<int> events = new List<int>();
using (var reader = new StreamReader(@"D:\Temp\AccessEmail.txt"))
try
{
string line;
while ((line = reader.ReadLine()) != null)
{
//split the line
string[] parts = line.Split(new[] { "Event" }, StringSplitOptions.None);
//get valid integers
plans.Add(GetInt(parts[0].Split(' ', '\'')));
events.Add(GetInt(parts[1].Split(' ', '\'')));
}
}
catch (System.Exception ex)
{
Console.WriteLine("Error" + ex.Message);
}
//print the elements in the lists
foreach (int x in plans)
{
Console.WriteLine(x);
}
foreach (int y in events)
{
Console.WriteLine(y);
}
//print the number of elements in the lists
Console.WriteLine(plans.Count);
Console.WriteLine(events.Count);
Console.ReadLine();
}
public static int GetInt(string[] a)
{
int i = 0;
foreach (string s in a)
int.TryParse(s, out i);
return i;
}
}
}
【问题讨论】:
-
您是否使用调试器来检查您尝试解析的值类型?如果您甚至不告诉我们它试图解析什么,我们怎么可能告诉您为什么
TryParse会失败? -
使用Debugger。它将帮助您了解正在发生的事情
-
嗨,tnw,我在文本文件中解析这样的行:“以前的错误是针对计划 ID '1111111' 事件 ID '33234042'”
标签: c#