C# 错误 CS0266:无法将类型“object”隐式转换为“int”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8894984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 05:01:33  来源:igfitidea点击:

error CS0266: Cannot implicitly convert type 'object' to 'int'

c#casting

提问by Br3x

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

错误 CS0266:无法将类型“object”隐式转换为“int”。存在显式转换(您是否缺少演员表?)

int dd= 6000;
sqlCmdDefaultTime = new SqlCommand("myQuery", sqlCon);
sqlDefaultTime = sqlCmdDefaultTime.ExecuteReader();
while (sqlDefaultTime.Read())
{
      dd= sqlDefaultTime[1];
}

how can i cast

我怎么投

采纳答案by ken2k

Simple cast to int:

简单转换为int

dd = (int)sqlDefaultTime[1];

回答by Chris

Integer.parseInt();

Integer.parseInt();

a few others such as TryParse and TryParseExact provide more functionality and control.

其他一些如 TryParse 和 TryParseExact 提供更多功能和控制。

dd= Integer.parseInt(sqlDefaultTime[1]); 

should do it, provided you can guarantee the value being returned is always an int.

应该这样做,前提是您可以保证返回的值始终为 int。

回答by musefan

Try this...

尝试这个...

int.TryParse(sqlDefaultTime[1].ToString(), out dd);

in the event that the parse is successful ddwill now be a new value.

如果解析成功,dd现在将是一个新值。

Unless of course the object is an int already, the you can just cast it...

除非该对象当然已经是一个 int ,否则您可以将其强制转换...

dd = (int)sqlDefaultTime[1];

回答by tpolyak

Instead of the indexer try to use the GetXXX methods of SqlDataReader:

尝试使用 SqlDataReader 的 GetXXX 方法代替索引器:

dd = sqlDefaultTime.GetInt32(1);

More GetXXX methods here: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx

这里有更多 GetXXX 方法:http: //msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx