2010-02-04 24 views
0

使用c#,當我有一個對象類型的變量時,如何利用可以使用空值的類型?使用c#,當我有一個對象類型的變量時,如何利用使用空值的值類型?

例如,我有一個類,它需要4個參數中的一個方法插入:

public int Update(Int32 serial, object deliveryDate, object quantity, object shiftTime) 
{ 
    .... 
    .... 
    .... 
} 

正如您可以猜到,這個方法在表中插入新記錄。該表(表1),有4個列:串行int,DeliveryDate日期時間空,數量浮動非空和ShiftTime smallint null

現在,我的quastion是:我如何利用使用可空值的值類型的好處,也可以轉換反對我喜歡的類型,如DateTime?

謝謝

回答

5

爲什麼你的對象類型的參數擺在首位?爲什麼不是:

public int Update(int serial, DateTime? deliveryDate, 
        double? quantity, short? shiftTime) 

(請注意,decimal可能比double一個更好的選擇 - 一些思考。)

如果你都不可能改變你的方法簽名,這可能是要走的路。

否則,你真的在​​你的問題中問什麼?如果不能更改參數,但參數應該是DateTime(或null),double(或null)和short(或null)類型的類型,那麼您可以將它們轉換爲它們的可空對應值。這將拆箱null的類型的空值,以及相應的非空值非空值:

object x = 10; 
int? y = (int?) x; // y = non-null value 10 
x = null; 
y = (int?) x; // y is null value of the Nullable<int> type 

編輯:爲了迴應評論...

假設你有一個文本換班時間。有三種選擇:填充但不恰當(例如「foo」),空白或有效。你會這樣做:

short? shiftTime = null; 
string userInput = shiftTimeInput.Text; 
if (userInput.Length > 0) // User has put *something* in 
{ 
    short value; 
    if (short.TryParse(userInput, out value)) 
    { 
     shiftTime = value; 
    } 
    else 
    { 
     // Do whatever you need to in order to handle invalid 
     // input. 
    } 
} 
// Now shiftTime is either null if the user left it blank, or the right value 
// Call the Update method passing in shiftTime. 
+0

喬恩,在GUI中,我有一個web表單,從用戶獲得4個值。 例如,窗體有一個用於ShiftTime的文本框。 但ShiftTime不是必填表單字段。所以用戶可能不會爲它輸入任何值。在這種情況下,我應該將Null傳遞給Table1中的ShiftTime列。我該如何處理這個問題? – odiseh 2010-02-04 07:36:08

+0

@odiseh:將編輯答案來解釋。 – 2010-02-04 07:37:33

+0

喬恩,非常感謝:) – odiseh 2010-02-04 08:00:19

2

你可以看看的System.Nullable<T>類型。它在C#中的一些快捷鍵:

public int Update(
    int serial, 
    DateTime? deliveryDate, 
    float? quantity, 
    short? shiftTime) 

,它允許你調用的方法是這樣的:

Update(10, null, null, null); 
相關問題