从细胞的DataRow INT解析 [英] Parsing int from DataRow cell
本文介绍了从细胞的DataRow INT解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
怎么可能int值从DataRow的细胞解析?
How could int value be parsed from DataRow cell?
Int32.Parse(item["QuestionId"].ToString());
这个代码的工作,但它看起来太冗长。
也是它能够处理DBNull的价值?
This code works, but it looks too verbose. Also is it possible to handle DBNull values?
推荐答案
如果你知道这是一个 INT
你应该只投它因此,这是最安全和最有效的方法:
If you know that it's an int
you should just cast it accordingly, that's the safest and most efficient approach:
int questionId = item.Field<int>("QuestionId"); // similar to (int) item["QuestionId"]
的
字段
法还支持可空类型,因此,如果它可能是空:
The Field
method also supports nullable types, so if it could be null:
int? questionId = item.Field<int?>("QuestionId");
if(questionId.HasValue) Console.Write(questionId.Value);
如果它实际上是一个字符串
(为什么? ),你必须将它转换为字符串
,并使用 int.Parse
:
If it's actually a string
(why?) you have to cast it to string
and use int.Parse
:
int questionId = int.Parse(item.Field<string>("QuestionId"));
如果你真的不知道它的类型是什么,您可以使用 System.Convert.ToInt32
:
If you really don't know what it's type is, you can use System.Convert.ToInt32
:
int questionId = System.Convert.ToInt32(item["QuestionId"]);
这篇关于从细胞的DataRow INT解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文