2010-02-10 54 views
5

我只是想知道如何編寫一個數字,必須表示爲字符串。最佳實踐條件與字符串和數字

例如:

if (SelectedItem.Value == 0.ToString()) ... 

if (SelectedItem.Value == "0") ... 

public const string ZeroNumber = "0"; 
if (SelectedItem.Value == _zeroNumber) ... 

if (Int.Parse(SelectedItem.Value) == 0) 
+0

WinForms或WebForms? – 2010-02-10 09:20:40

+3

@Asad Butt - 爲什麼在這裏重要? – Oded 2010-02-10 09:22:01

回答

9

對於一個測試,我會親自去與

if (SelectedItem.Value == "0") 

它有沒有什麼大驚小怪的,沒有儀式 - 它說你想要做什麼。

在另一方面,如果我有這應該是一個數字,然後我就反應過來基於該數的值,我會使用:

int value; 
// Possibly use the invariant culture here; it depends on the situation 
if (!int.TryParse(SelectedItem.Value, out value)) 
{ 
    // Throw exception or whatever 
} 
// Now do everything with the number directly instead of the string 
1

使用TryParse

string value = "123"; 
int number; 
bool result = Int32.TryParse(value, out number); 
if (result) 
{ 
    ... 
2

如果該值意味着是一個整數,這是它應該自然地使用,那麼我就解析爲int - 即使用最適合於數據的意義類型。

例如,經常從數據庫查找表中填充下拉列表 - 如果將項目鍵存儲爲整數,那麼我認爲您應該始終如一地處理它。同樣,如果所選項目的關鍵字再次存儲在數據庫中,則無論如何都需要將其轉換爲int。