2014-10-17 27 views
-2

我有一個簡單的問題。將對象DBNULL轉換爲float.tryparse或運算符?:

場景:當用戶沒有填充場速時更新數據的方法(dt.Row [9])。

//Car.speed is float and dt.row[9] is a object 

float speedo; 
float.TryParse(dt.Row[9].ToString(), out speedo); 
Car.speed = speedo 

Car.speed = dt.Row[9].ToString().Equals(string.Empty) ? 0 : Convert.ToSingle(dt.Row[9]) 

考慮到性能和良好的代碼,什麼是更好的?任何建議?

我知道這不是什麼大不了的事情,但是我有許多具有float類型屬性的類。所以它只是讓代碼更乾淨。

+0

的[可能的可能重複使用? (合併運算符)與DBNull?](http://stackoverflow.com/questions/9436852/possible-to-use-the-coalesce-operator-with-dbnull) – 48klocs 2014-10-17 20:43:29

回答

-1

然後我看一些類似的問題,比如Abe's question和我的代碼更改爲:

Car.speed = DBNULL.value.Equals(dt.Row[9]) ? 0 : Convert.ToSingle(dt.Row[9]) 

後來我決定用一個新的類使用asawyer'method(來自同一個鏈接),就像這樣:

public static class ExtensionDBNull 
    { 

public static float DBNullToFloat(this object TheObject, object DefaultValue) 
    { 

     return DBNull.Value.Equals(TheObject) ? 0 : Convert.ToSingle(TheObject); 

     //if (TheObject is DBNull) 
     // return DefaultValue; 
     //return Convert.ToSingle(TheObject); 

    } 
    } 

所以現在我有

Car.speed = ExtensionDBNull.ObjectToFloat(dt.row[9],0);