2016-05-23 8 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 

} 

、すべてがdoubleとして宣言されています。私はきれいにして、ソリューションを何度も再利用しようとしました。私は何が欠けていますか?

+9

'公共のintは... ' –

+0

あなたの関数はdDispositionを返す'、int'ので '返すように宣言されました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) 

または変数dDispositionconverter methodの種類:; `二重に変換しようとしている

int dDisposition = 0; 

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

return dDisposition; 
+1

intへのキャストはより慣用的です。 –

+0

ありがとう@Nahuel Ianni。私は何かが足りないことを知っていた。 – mack

関連する問題