以下例子,你以为有什么题目?如你能很快的找出题目,而且处理它,那末你能够跳过本篇文章,感谢~~。
1 List<Base_Employee> ltPI = new List<Base_Employee>(); 2 DataTable dt = GetBase_UserInfoToDataTable(); 3 for (int i = 0; i < dt.Rows.Count; i++) 4 { 5 Base_Employee base_Employee= new Base_Employee(); 6 base_Employee.EmployeeId= dt.Rows[i]["EmployeeId"].ToString();//EmployeeId为string范例 7 base_Employee.Age =(int)dt.Rows[i]["Age"];//Age为int范例 8 base_Employee.GraduationDate = (DateTime)dt.Rows[i]["GraduationDate"];//GraduationDate 为DateTime范例 9 }
想一分钟,OK,假如没想出来,能够往下看,下图标注处即为题目处。
ok,本篇文章就是来处理该题目的。也就是接下来要与人人分享的System.DBNULL范例
2 内容分享
2.1 在.NET中的,经常使用的基础数据范例
int,string,char等是人人比较熟习的基础数据范例,然则大部分人都应该对System.DBNull比较生疏,但是,它又是处理如上题目的一大思绪。
2.2 SqlServer中的经常使用数据范例
varchar,nvarchar,int,bit,decimal,datetime等,基础在与.net中的数据范例一一对应(varchar和nvarchar均对应.net中的string范例)
2.3 SqlServer中的经常使用数据范例的初始值
在.net中,当我们定义一个变量时,假如没给其赋初始值,那末体系会默许初始值,如int 范例默许为0,string范例默许为string.Empty,平常状况,差别范例的默许初始值是差别的;然则,在SqlServer中,险些一切变量范例的初始值为NULL,也就要么为用户自定义的值,要么为体系默许的值NUL。题目的症结就在这,以int范例为例,当在数据库中,我们没有给INT赋值时,其默许值为NULL,当把这个值赋给.net中的整形变量时,就会激发非常。
2.4 System.DBNull是什么?
DBNull是一个类,继续Object,其实例为DBNull.Value,相当于数据中NULL值。
2.5 为何 DBNull能够示意其他数据范例?
在数据库中,数据存储以object来存储的。
2.6 怎样处理如上题目
加前提推断
能够用string范例是不是为空,或DBNull是不是即是NULL来推断
1 List<Base_Employee> ltPI = new List<Base_Employee>(); 2 DataTable dt = GetBase_UserInfoToDataTable(); 3 for (int i = 0; i < dt.Rows.Count; i++) 4 { 5 Base_Employee base_Employee= new Base_Employee(); 6 base_Employee.EmployeeId= dt.Rows[i]["EmployeeId"].ToString();//EmployeeId为string范例 7 //base_Employee.Age =(int)dt.Rows[i]["Age"];//Age为int范例 8 if (dt.Rows[i]["Age"]!=System.DBNull.Value) 9 { 10 base_Employee.Age = int.Parse(dt.Rows[i]["Age"].ToString()); 11 //base_Employee.Age = (int)dt.Rows[i]["Age"];//拆箱 12 //base_Employee.Age =Convert.ToInt16( dt.Rows[i]["Age"]); 13 } 14 //base_Employee.GraduationDate = (DateTime)dt.Rows[i]["GraduationDate"];//GraduationDate 为DateTime范例 15 if (dt.Rows[i]["GraduationDate"].ToString()!="") 16 { 17 base_Employee.GraduationDate = Convert.ToDateTime(dt.Rows[i]["GraduationDate"]); 18 base_Employee.GraduationDate = (DateTime)dt.Rows[i]["GraduationDate"]; 19 } 20 }
以上就是C#中关于DBNULL的诠释的细致内容,更多请关注ki4网别的相干文章!