2014-01-24 15 views
6

在我的應用程序中,我有一個文本框 - txtDiscount,管理員可以爲某個用戶設置折扣百分比,或者他可能不會。在後端我要保存的數據,所以現在我有這樣的:如何在輸出允許爲空時使用double.TryParse?

double? discount = null; 
if (!string.IsNullOrEmpty(txtDiscount.Text)) 
{ 
    if (!double.TryParse(txtDiscount.Text, out discount)) errors.Add("Discount must be a double."); 
} 

所以我得到一個錯誤的invalid argument,顯然它是discount如果我要使用它TryParse無法可空。我看到很多人都在爲這種情況進行擴展,但現在我不認爲這是必要的。我能想到的使用另一個變量,像這樣的:

double? discount = null; 
private double _discount; 
if (!string.IsNullOrEmpty(txtDiscount.Text)) 
{ 
    if (!double.TryParse(txtDiscount.Text, out _discount)) 
    { 
    errors.Add("Discount must be adouble."); 
    } 
    else 
    { 
    discount = _discount; 
    } 
} 

,然後用我的可空discount的值傳遞給數據庫。但我其實不喜歡上面的代碼,在我看來,這樣的任務相當複雜,但我想不出更好的東西。那麼如何處理這種情況而不使用擴展方法呢?

+3

爲什麼你過於複雜的應用程序通過處理特殊情況設計:

就個人而言,我只是與分析可空雙擴展名去了?爲什麼系統總是假設折扣價值(0.0),並且只有當有人改變這一點時,你纔會得到一個新的數字。當每個計算總是包含折扣(即使它是0.0),那麼你不需要特殊的處理。對於你的GUI你確實需要一些空字符串檢查,但不要犯錯誤,並在你的前端反映數據庫設計。 – Samuel

+0

那麼,在這種情況下,我認爲可以爲空,因爲'0.0'仍然是一個值,你可以告訴用戶有0.0%的折扣,當可爲空時表示這個用戶實際上沒有折扣,更有意義。但即使我的問題更一般,即使我要將該類型更改爲「dobule」,我仍然想看看如何處理這種情況,它看起來像很標準的東西。 – Leron

+0

@Leron如果折扣是負面的? –

回答

4

你可以做解析,而不擴展方法 - 只使用當地的非空值將它傳遞給方法的TryParse:

double? discount = null; 

if (!String.IsNullOrEmpty(txtDiscount.Text)) 
{ 
    double value; 
    if (Double.TryParse(txtDiscount.Text, out value))  
     discount = value; 
    else  
     errors.Add("Discount must be a double."); // discount will have null value 
} 

但我搬到這一切邏輯的延伸。

+1

你不覺得如果條件和它的身體是完全多餘的。這不會改善任何東西從OP的代碼 –

+0

@SriramSakthivel謝謝!錯過了那件事(因爲試圖首先使用三元運算符) –

-1
Nullable<double> discount = new Nullable<double>(); 

默認值是媒體鏈接空你不需要它設置爲null再次

1
static void Main() 
{ 
    var testStrings = new[] { "", "1.234" }; 

    foreach(var testString in testStrings) 
    { 
     double output; 
     double? value = null; 

     if(double.TryParse(testString, out output)) 
     { 
      value = output; 
     } 

     Console.WriteLine("{0}", value.HasValue ? value.Value.ToString() : "<null>"); 
    } 
} 
-1
if(double.TryParse(txtDiscount.Text?? "", out _discount)) 
    discount=_discount; 
else Console.WriteLine("Discount must be adouble."); 
3

你只是將不得不與當地的一個非可空類型寫醜陋的代碼或者使用另一種方式定義沒有折扣。我同意一個可爲空的double是表示它的一種簡潔的方式,但是如果代碼讓你惱火,那麼嘗試一些不同的東西(例如:bool,例如:discount_given = true)。

public static bool ParseDouble(string s, out double? dd) 
    { 
     double d; 
     bool ret = double.TryParse(s, out d); 

     if (ret) 
      dd = d; 
     else 
      dd = null; 

     return ret; 
    } 
0
public static double ToDouble(this string value, double fallbackValue = 0) 
    { 
     double result; 

     return double.TryParse(value, out result) ? result : fallbackValue; 
    }