2009-01-01 76 views

回答

59

Int32.TryParse(String, Int32) - http://msdn.microsoft.com/en-us/library/f02979c7.aspx

bool result = Int32.TryParse(value, out number); 
    if (result) 
    { 
    Console.WriteLine("Converted '{0}' to {1}.", value, number);   
    } 
+0

我一直在編輯它,所以任何錯誤可能已被糾正 – 2009-01-01 23:04:13

11

你能不能讓它多了幾分雅緻通過運行的TryParse右轉入如果?

像這樣:

if (Int32.TryParse(value, out number))  
    Console.WriteLine("Converted '{0}' to {1}.", value, number); 
0

發現這個在搜索結果中的一個:How do I identify if a string is a number?

添加這個,因爲我之前看過的答案沒有用法:

int n; 
bool isNumeric = int.TryParse("123", out n); 

這裏"123"可以是類似於OP正在測試的字符串s = "123"以及值n將具有值(123),如果它被發現是數字。