爲什麼你的對象類型的參數擺在首位?爲什麼不是:
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.
喬恩,在GUI中,我有一個web表單,從用戶獲得4個值。 例如,窗體有一個用於ShiftTime的文本框。 但ShiftTime不是必填表單字段。所以用戶可能不會爲它輸入任何值。在這種情況下,我應該將Null傳遞給Table1中的ShiftTime列。我該如何處理這個問題? – odiseh 2010-02-04 07:36:08
@odiseh:將編輯答案來解釋。 – 2010-02-04 07:37:33
喬恩,非常感謝:) – odiseh 2010-02-04 08:00:19