如何在C#中的整数变量中存储空值 [英] how to store null values in integer variable in C#

查看:160
本文介绍了如何在C#中的整数变量中存储空值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用这些代码将null值存储到整数变量....



I couldn't store null value to an integer variable using these codes ....

int? i = Convert.ToInt32(orderqty.Text);
            int? counts = !string.IsNullOrEmpty(orderqty.Text) ? i : (int?)null;

            int? i1 = Convert.ToInt32(yarncounts.Text);
            int? counts1 = !string.IsNullOrEmpty(yarncounts.Text) ? i1 :(int?)null;



有没有最好的方法可以将空值存储到counts1变量?


Is there any best methods to store null values to counts1 variable ??

推荐答案

为什么?

这是一些奇怪的代码:你做的转换为整数 - 将失败的是字符串为空 - 然后测试它是否为空或空...

先检查,然后转换:

Why?
That is some odd code: you do a conversion to integer - which will fail is the string is empty - then test to see if it's null or empty...
Check first, then convert:
int? counts1 = string.IsNullOrEmpty(yarncounts.Text) ? (int?)null : int.Parse(yarncounts.Text);


你应该像这样优化代码:

int? counts1 =(string.IsNullOrEmpty(yarncounts.Text)?(int?)null:Convert.ToInt32(yarncounts.Text);
You should optimize the code like this:
int? counts1 = (string.IsNullOrEmpty(yarncounts.Text) ? (int?)null : Convert.ToInt32(yarncounts.Text);


没有必要将null转换为(int?)。

另外,使用int.TryParse会捕获其他无效输入:

It isn't necessary to cast the null to (int?).
Also, using int.TryParse would catch other invalid input:
int? counts1 = null;
int i1;
if (int.TryParse(yarncounts.Text, out i1))
{
  counts1 = i1;
}
else
{
  // here you can perform any additional error handling/reporting (but you don't HAVE to!)
}


这篇关于如何在C#中的整数变量中存储空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆