2010-01-14 106 views
1
int age = txtAge.Text; 

,我發現了錯誤:類型轉換錯誤

Error 2 Cannot implicitly convert type 'string' to 'int' 

回答

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); 
+0

注意,你應該檢查是從'TryParse'返回'bool',和國際海事組織這是更爲常見看到'int'而不是'Int32'(儘管如此)。 – 2010-01-14 06:23:37

+0

第一個我可以同意,第二個(int與Int32)取決於公司內的編程慣例。我的公司約定狀態:使用int表示聲明和顯式轉換,Int32用於靜態方法調用。 但當然這是所有政策的主觀:)。 – Webleeuw 2010-01-14 06:45:56