C# DBNull 和可为空类型 - 最干净的转换形式 [英] C# DBNull and nullable Types - cleanest form of conversion

查看:25
本文介绍了C# DBNull 和可为空类型 - 最干净的转换形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 DataTable,它有许多列.其中一些列可以为空.

I have a DataTable, which has a number of columns. Some of those columns are nullable.

DataTable dt;  // Value set. 
DataRow dr;  // Value set. 

// dr["A"] is populated from T-SQL column defined as: int NULL 

那么,从 DataRow 中的值转换为可为空变量的最简洁的形式是什么.

What, then, is the cleanest form of converting from a value in a DataRow, to a nullable variable.

理想情况下,我可以执行以下操作:

Ideally, I would be able to do something like:

int? a = dr["A"] as int?; 

编辑:事实证明你可以这样做,副作用是如果你的架构类型不是整数,那么这总是会返回空值.Ruben 使用 dr.Field("A") 的答案确保类型不匹配不会默默地失败.当然,这将通过彻底的单元测试来实现.

Edit: Turns out you CAN do this, the side effect being that if your Schema types arn't ints, then this is ALWAYS going to return null. The answer by Ruben of using dr.Field<int?>("A") ensures type mismatches don't silently fail. This, of course, will be picked up by thorough unit tests.

相反,我通常会输入以下内容:

Instead I'm usually typing something along the lines of:

int? a = dr["A"] != DBNull.Value ? (int)dr["A"] : 0; 

这是更多的按键,但更重要的是,有人有更多的空间用错误的按键来填充某些东西.是的,单元测试会解决这个问题,但我宁愿完全停止.

This is a bunch more keystrokes, but more importantly, there's more room for someone to stuff something up with a wrong keystroke. Yes, a Unit Test will pick this up, but I'd rather stop it altogether.

在这种情况下,最干净、最不容易出错的模式是什么?

What is the cleanest, least error-prone pattern for this situation.

推荐答案

LINQ in Action 的 LINQ to DataSets 章节 是一本很好的读物.

您将看到的一件事是 Field 扩展方法,其用法如下:-

One thing you'll see is the Field<T> extension method, which is used as follows:-

int? x = dr.Field<int?>( "Field" );

int y = dr.Field<int?>( "Field" ) ?? 0;

var z = dr.Field<int?>( "Field" );

这篇关于C# DBNull 和可为空类型 - 最干净的转换形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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