我在将字符串数组中的值转换为 int 时遇到问题,因为该值可能为空。
StreamReader reader = File.OpenText(filePath);
string currentLine = reader.ReadLine();
string[] splitLine = currentLine.Split(new char[] { '|' });
object.intValue = Convert.ToInt32(splitLine[10]);
除了当 splitLine[10] 为 null 时,这很好用。
抛出错误:`System.FormatException:输入字符串的格式不正确。
有人可以就处理此问题的最佳方法向我提供一些建议吗?
最佳答案
不要用convert,最好用
int.TryParse()
例如
int val = 0;
if (int.TryParse(splitLine[10], out val))
obj.intValue = val;
关于c# - 当可能为空字符串值时,将字符串数组值转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11144520/