C# 错误';无法将double转换为int';
在我看来,我的代码有一个奇怪的问题。我有一个执行简单查询并返回结果的方法。我试图以双精度返回值,但出现错误: CS0266无法将类型“double”隐式转换为“int”。明确的 存在转换(您是否缺少演员阵容?) 我不想做任何转换,所以我不明白问题是什么。 以下是呼叫代码:C# 错误';无法将double转换为int';,c#,compiler-errors,type-conversion,C#,Compiler Errors,Type Conversion,在我看来,我的代码有一个奇怪的问题。我有一个执行简单查询并返回结果的方法。我试图以双精度返回值,但出现错误: CS0266无法将类型“double”隐式转换为“int”。明确的 存在转换(您是否缺少演员阵容?) 我不想做任何转换,所以我不明白问题是什么。 以下是呼叫代码: double displacement = sqLite.GetDisplacement( transItem.Item.Name ); 以下是代码,称为: public int GetDisplacement( str
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
}
我不想转换任何东西,所有东西都声明为双精度。我多次尝试清理和重建解决方案,但都没有成功。我缺少什么?方法声明声明将返回
int
值:
public int GetDisplacement (string item)
但是在代码上,return语句返回的变量类型为double
:
double dDisposition = 0;
// Your code here
return dDisposition;
您必须更改其中一个,因此基本上更改返回类型:
public double GetDisplacement (string item)
或dDisposition
变量的类型和:
public int…
为您将来遇到此问题提供建议。大声阅读你的代码,你会很快发现问题。另外,停止使用匈牙利语的应用程序。在C#中,不需要用变量的类型来注释变量。如果要用变量的类型注释变量,请使其有意义,如itemsont
或itemsIndex
,切勿itemsInt
;我们不知道int是计数还是索引。如果你想知道一个变量是双精度变量还是字符串,请看它的声明,而不是它的名称。你的代码也有SQL注入安全漏洞。还有,为什么保存置换的变量称为“disposition”?将其转换为int更为惯用。谢谢@Nahuel Ianni。我知道我错过了什么。
int dDisposition = 0;
// Your code here
dDisposition = Convert.ToInt32(result);
// More of your code here
return dDisposition;