gpt4 book ai didi

c# - 当可能为空字符串值时,将字符串数组值转换为 int

转载 作者:太空宇宙 更新时间:2023-11-03 17:43:31 25 4
gpt4 key购买 nike

我在将字符串数组中的值转换为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com