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

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

问题描述

我有一个DataTable,它有一些列。其中一些列为空。

  DataTable dt; //设置值
DataRow dr; //设置值

// dr [A]从T-SQL列中填充,定义为:int NULL

那么,将DataRow中的值转换为可变变量的最干净的形式呢?



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

  int? a = dr [A] as int? 

编辑:原来你可以做到这一点,效果是,如果您的Schema类型不是int,那么这一直是返回null。 Ruben使用 dr.Field< int?>(A)的答案确保类型不匹配不会静默失败。当然,这将通过彻底的单元测试来获取。



相反,我通常会按照以下方式输入内容:

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

这是一个更多的按键,但更重要的是,有更多的空间给某人填充一些东西键击错误
是的,单元测试会选择这个,但我宁愿完全停止。



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

解决方案

LINQ to DataSets LINQ in Action 的一章很好阅读。



<有一件事你会看到的是 Field< T> 扩展方法,其用法如下: -

  int? x = dt.Field< int?>(Field); 

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

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


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 

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?; 

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.

解决方案

The LINQ to DataSets chapter of LINQ in Action is a good read.

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

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

Or

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

Or

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

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

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