1
我正在使用下面的代碼來實現我想要的功能:當用戶在特定的NumericUpDown控件中編輯一個值,並按下k
,K
,m
或M
,我希望當前輸入的金額乘以1000
。我也希望避免任何溢出異常。值應自動限制在minimum
和maximum
。我不想使用if
語句,因爲min
和max
函數可用。但是,它需要一些精力來處理該邏輯(應用min
到maximum
和max
到minimum
...什麼?),我覺得我需要留言:'警告,這個代碼很難閱讀,但它的作品'。這不是我應該寫的評論。邏輯太簡單了,不需要評論,但我找不到表達它的自我表達方式。有什麼建議麼?我可以使用控件本身的設置/方法來完成這個任務嗎?尋找整潔,直觀,慣用的方法來剪輯我在使用C#的NumericUpDown控件中設置的值?
private void quantityNumericUpDown_KeyUp(object sender, KeyEventArgs e)
{
if (e.Control || e.Alt)
{
e.Handled = false;
return;
}
if (e.KeyCode != Keys.K && e.KeyCode != Keys.M)
{
e.Handled = false;
return;
}
e.SuppressKeyPress = true;
e.Handled = true;
this.Quantity *= OneThousand;
}
private decimal Quantity
{
get
{
return this.quantityNumericUpDown.Value;
}
set
{
// Sorry if this is not the most readable.
// I am trying to avoid an 'out of range' exception by clipping the value at min and max.
decimal valClippedUp = Math.Min(value, this.quantityNumericUpDown.Maximum);
this.quantityNumericUpDown.Value = Math.Max(valClippedUp, this.quantityNumericUpDown.Minimum);
}
}
我想過這個......它很簡潔,但它沒有同樣的問題 - 在同一行上有太多最小和最大值?我認爲很難立即得到意圖。 –