2016-05-23 156 views
-2

我對我的代碼有一種奇怪的問題。我有一個方法執行一個簡單的查詢並返回結果。我試圖返回的值作爲雙,但我得到一個錯誤:錯誤'不能將double轉換爲int'

CS0266 Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)

我不想做任何轉換,所以我不知道是什麼問題。 下面是調用代碼:

double displacement = sqLite.GetDisplacement(transItem.Item.Name); 

,這裏是被稱爲代碼:

public int GetDisplacement(string item) 
{ 
    double dDisposition = 0; 
    string sSql = "SELECT [Displacement] FROM [Items] WHERE [Name] = '" + item + "';"; 

    using (var dbConnection = new SQLiteConnection(sConnectionString)) 
    { 
     try 
     { 
      dbConnection.Open(); 
      SQLiteCommand cmd = new SQLiteCommand(sSql, dbConnection); 
      object result = cmd.ExecuteScalar(); 

      dDisposition = Convert.ToDouble(result); 

     } 
     catch (Exception e) 
     { 
      MessageBox.Show("Error retreiving displacement information: " + e.ToString()); 
     } 

    } 

    return dDisposition; // This is where I get the error 

} 

我並不想的東西轉換,一切都被聲明爲雙。我試圖清理和重建解決方案多次無濟於事。我錯過了什麼?

+9

'公衆詮釋...' –

+0

你的函數聲明爲返回'int'所以,'返回dDisposition;'正試圖轉換到雙int – Plutonix

+1

當你在將來遇到這個問題的時候,建議一下。大聲閱讀你的代碼**,你會很快發現問題。 –

回答

1

方法聲明中指出的int值將返回:

public int GetDisplacement (string item) 

但在代碼中,return語句返回double類型的變量:

double dDisposition = 0; 

// Your code here 

return dDisposition; 

你必須改變所以基本上改變了返回類型:

public double GetDisplacement (string item) 

還是dDisposition變量和converter method類型:

int dDisposition = 0; 

// Your code here 
dDisposition = Convert.ToInt32(result); 
// More of your code here 

return dDisposition; 
+1

強制轉換爲int會更習慣。 –

+0

謝謝@Nahuel Ianni。我知道我錯過了一些東西。 – mack

相關問題