c# - 我收到“输入字符串不是给定格式”错误,因为在我的文本文件中输入的 Id 值
问题描述
我收到这条线的错误 me.Id = int.Parse(cols[0]); 在我的文本文件中输入。我正在解析我的字符串,但是当我调试文件时它给出了空白字符串“”。谁能帮我解决文件
public static List<MatchupEntryModel> ConvertToMatchupEntryModels(this List<string> lines)
{
//id = 0, TeamCompeting = 1, Score = 2, ParentCompeting = 3
List<MatchupEntryModel> output = new List<MatchupEntryModel>();
foreach(string line in lines)
{
string[] cols = line.Split(',');
MatchupEntryModel me = new MatchupEntryModel();
me.Id = int.Parse(cols[0]);
if(cols[1].Length == 0)
{
me.TeamCompeting = null;
}
else
{
me.TeamCompeting = LookupTeamById(int.Parse(cols[1]));
}
me.Score = double.Parse(cols[2]);
int parentId = 0;
if(int.TryParse(cols[3], out parentId))
{
me.ParentMatchup = LookupMatchupById(parentId);
}
else
{
me.ParentMatchup = null;
}
output.Add(me);
}
return output;
//List<PersonModel> output = new List<PersonModel>();
//foreach (string line in lines)
//{
// string[] cols = line.Split(',');
// PersonModel p = new PersonModel();
// p.Id = int.Parse(cols[0]);
// p.FirstName = cols[1];
// p.LastName = cols[2];
// p.EmailAddress = cols[3];
// p.CellphoneNumber = cols[4];
// output.Add(p);
//}
//return output;
}
我还将我的保存条目发送到用于保存文件的文件功能。
public static void SaveEntryToFile(this MatchupEntryModel entry, string matchupEntryFile)
{
List<MatchupEntryModel> entries =
GlobalConfig.MatchupEntryFile.FullFilePath().LoadFile().ConvertToMatchupEntryModels();
int currentId = 1;
if(entries.Count > 0)
{
currentId = entries.OrderByDescending(x => x.Id).First().Id + 1;
}
entry.Id = currentId;
entries.Add(entry);
List<string> lines = new List<string>();
//id = 0, TeamCompeting = 1, Score = 2, ParentCompeting = 3
foreach (MatchupEntryModel e in entries)
{
string parent = "";
if(e.ParentMatchup != null)
{
parent = e.ParentMatchup.Id.ToString();
}
string teamCompeting = "";
if(e.TeamCompeting != null)
{
teamCompeting = e.TeamCompeting.Id.ToString();
}
lines.Add($"{ e.Id }, { teamCompeting }, { e.Score }, { parent }");
}
File.WriteAllLines(GlobalConfig.MatchupEntryFile.FullFilePath(), lines);
//foreach (TeamModel t in models)
//{
// lines.Add($"{ t.Id }, { t.TeamName }, { ConvertPeopleListToString(t.TeamMembers)}");
//}
//File.WriteAllLines(fileName.FullFilePath(), lines);
}
解决方案
使用 TryParse 而不是 Parse。它将返回 0 而不是抛出异常。
推荐阅读
- c++ - 为什么我的代码中出现“运行时错误 - SIGSEGV”?
- linux - Systemd 服务已启用但未启动
- anychart - AnyCharts AnyMap中未选中状态的背景
- java - python中的AES加密和java中的解密不起作用
- uwp - 如何在数据模板中获取 x:name
- python - 将 diff() 应用于熊猫多索引级别?
- javascript - 如何将流包装到异步中,使其在启动流之前等待名称解析
- python - 如何继续更新 for 循环中的特定列表?
- python-3.x - 在 Microsoft 翻译器中翻译文本会删除 //
- angular-cli - 使用 ng build 在 Angular 库中构建外部 JS(不是 TS)文件?