Q
類型轉換錯誤
1
A
回答
2
int age = int.Parse(txtAge.Text);
1
嘗試
int age;
bool result = Int32.TryParse(txtAge.Text, out age);
if (result)
{
// Parse succeeded and get the result in age
}
else
{
// Parse failed
}
見Int32.TryParse Method (String, Int32)
The TryParse method is like the Parse method, except the TryParse method does not throw an exception if the conversion fails. It eliminates the need to use exception handling to test for a FormatException in the event that s is invalid and cannot be successfully parsed.
2
當然可以」 t,int和string是兩種完全不同的類型。然而,最簡單的解決辦法是:
int age = Int32.Parse(txtAge.Text);
更安全的是:
int age;
Int32.TryParse(txtAge.Text, out age);
相關問題
- 1. 在類型轉換錯誤
- 2. 類型轉換錯誤,c#
- 3. 類型轉換錯誤
- 4. GSON類型轉換錯誤
- 5. MySQL的函數類型轉換錯誤
- 6. Newtonsoft.json將333錯誤轉換爲類型
- 7. Coos2dx中的類型轉換錯誤
- 8. MPI_Irecv類型轉換所需錯誤
- 9. 數據類型轉換錯誤
- 10. 雙倍字節類型轉換錯誤
- 11. MediaLibrary Delphi類型轉換錯誤
- 12. Flink - Datastream類型轉換 - 錯誤
- 13. 無法隱式轉換類型錯誤
- 14. LuaJ錯誤返回類型轉換
- 15. 關於Python類型轉換的錯誤
- 16. 錯誤:轉換爲非標量類型
- 17. Spring 3類型轉換錯誤
- 18. PHP類型轉換錯誤更改值
- 19. 隱式類型轉換 - 編譯錯誤
- 20. 類型轉換錯誤通用
- 21. LINQ中的類型轉換錯誤
- 22. 奇怪的類型轉換錯誤
- 23. C# - Linq to SQL,類型轉換錯誤
- 24. C++類型轉換:錯誤C2440:'=':無法從'short *'轉換爲'DCTBLOCK'
- 25. 轉換數據類型(varchar)仍然顯示轉換錯誤
- 26. 錯誤:從'DBNull'類型到'String'類型的轉換無效
- 27. 類型錯誤:無法返回值轉換爲所需類型
- 28. javac錯誤:不可轉換類型與泛型?
- 29. 錯誤:(26,24)錯誤:不兼容的類型:類不能轉換到碎片
- 30. C++自動類型轉換:容器類的錯誤行爲
注意,你應該檢查是從'TryParse'返回'bool',和國際海事組織這是更爲常見看到'int'而不是'Int32'(儘管如此)。 – 2010-01-14 06:23:37
第一個我可以同意,第二個(int與Int32)取決於公司內的編程慣例。我的公司約定狀態:使用int表示聲明和顯式轉換,Int32用於靜態方法調用。 但當然這是所有政策的主觀:)。 – Webleeuw 2010-01-14 06:45:56