从 DataRow 单元格中解析 int 值

12

如何从DataRow单元格解析int值?

Int32.Parse(item["QuestionId"].ToString());

这段代码可以运行,但是看起来太啰嗦了。 还有,能否处理 DBNull 值?


1
只是为了确认一下:你为什么要说“解析”?QuestionId的类型实际上是否类似于字符串,例如VARCHAR - Matthias Meid
不,QuestionId的类型是int。但如果它像字符串一样呢? - Anthony
你可以使用 Int32.TryParse。 - Denis
@Anthony 如果它类似于字符串,我会在您的帖子中使用int.Parse来完成,而当它已经是数字类型时,Jeppe的解决方案更好。 - Matthias Meid
2个回答

24

如果你知道它是一个 int,那么你应该根据需要将其转换为 int,这是最安全和最有效的方法:

int questionId = item.Field<int>("QuestionId");  // similar to (int) item["QuestionId"]

Field方法也支持可空类型,因此如果它可能为null:

int? questionId = item.Field<int?>("QuestionId");
if(questionId.HasValue) Console.Write(questionId.Value);

如果它实际上是一个string(为什么?),那么您必须将其转换为string并使用int.Parse


如果实际上是一个字符串(为什么?),您需要将其强制转换为字符串并使用int.Parse:
int questionId = int.Parse(item.Field<string>("QuestionId"));

如果你真的不知道它的类型是什么,你可以使用System.Convert.ToInt32

int questionId = System.Convert.ToInt32(item["QuestionId"]);

.NET 2.0 不支持,是吗? - Khanh TO
1
@KhanhTO 不是的,Field 是一个扩展方法,它是在3.5版本中添加的。 - sloth
@KhanhTO 不,Field<T> 方法是一个扩展方法,仅在 .NET 3.5+ 中可用。 - Trevor Pilley
@Tim Schmelter,int? questionId = item.Field<int?>("QuestionId"); 这样写是否可以安全地处理 DbNull 值? - Sanjeev Rai

7

如果放入单元格中的内容实际上只是一个int,则使用:

(int)item["QuestionId"]

否则,检查值item["QuestionId"]的运行时类型,如果是byte,那么使用(byte)item["QuestionId"]。 如果不确定,则:

Convert.ToInt32(item["QuestionId"])

这样做也许能够运行,但这种方法不够优雅。


@Wouter Huysentruit:如果有一个NULL值,会抛出异常吗? - Khanh TO
如果不想抛出异常,而是希望在值为 null 时返回默认值,请考虑使用 (int?)item["QuestionId"] - Jeppe Stig Nielsen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接