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

标签 c# null int arrays

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

相关文章:

C# 正则表达式 : An object reference is required for the non-static field, 方法,或属性 'Regex.Match(string)'

Mysql IN(VARCHAR) 与 IN(INT)

java - 为什么增量运算符不总是对字符起作用?

c# - 强制 MySQL Connector.NET 返回一个 bool 值

c# - 传入请求的参数过多。服务器最多支持2100个参数

c# - 我可以在我的 .NET 2 应用程序中运行 .NET 4 应用程序吗?

java - GSON : Treat Empty String as null

hadoop - NULL 在将 Hive 查询结果写入文本文件时显示为 '\N'

php - 使用 PHP 从 MySQL 中删除 NULL 值的问题

c - Linux - 为什么自定义系统调用不能正常使用负数?