验证DataTable行中的空值

时间:2018-08-13 18:30:59

标签: c#

我有一个简单的字符串变量,例如:

var currentMedianEmployeeProgressToBackcheck = "";

我将其填充为:

var EmployeeMedian = (from DataRow dr in dtEmployeeMedian.Rows
                      select new
                      {
                          MedianEmployeeProgressToBackcheck = dr["MedianEmployeeProgressToBackcheck"]
                      }).FirstOrDefault();

currentMedianEmployeeProgressToBackcheck = EmployeeMedian.MedianEmployeeProgressToBackcheck.ToString();

但是当它为null时,它将抛出null异常:

  

System.NullReferenceException:'对象引用未设置为   对象的实例。'

     

EmployeeMedian为空。

如何在执行该空变量之前对其进行验证?问候

我尝试简单的方法,例如:

 if (EmployeeMedian.MedianEmployeeProgressToBackcheck != null){}

但不起作用

1 个答案:

答案 0 :(得分:3)

如果Null propagation operator是C#6或更高版本(如下面所示),则可以确保仅在实例不为null时执行操作:

currentMedianEmployeeProgressToBackcheck = EmployeeMedian?.MedianEmployeeProgressToBackcheck?.ToString();

否则,您将需要在访问条件之前放置一个if条件,以确保您未在​​空引用上调用它,例如:

if(EmployeeMedian !=null && EmployeeMedian.MedianEmployeeProgressToBackcheck != null)
{
   currentMedianEmployeeProgressToBackcheck = EmployeeMedian.MedianEmployeeProgressToBackcheck.ToString();
}