C# 不能隐式转换类型“int?” 到'int'。

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16798269/
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-10 07:47:54  来源:igfitidea点击:

Cannot implicitly convert type 'int?' to 'int'.

c#executescalar

提问by MaylorTaylor

I'm getting the error "Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)" on my OrdersPerHour at the return line. I'm not sure why because my C# skills are not that advanced. Any help would be appreciated.

我收到错误“无法隐式转换类型 'int?' 到'int'。在返回行的我的 OrdersPerHour 上存在显式转换(您是否缺少演员表?)”。我不知道为什么,因为我的 C# 技能不是那么高级。任何帮助,将不胜感激。

static int OrdersPerHour(string User)
{
    int? OrdersPerHour;
    OleDbConnection conn = new OleDbConnection(strAccessConn);
    DateTime curTime = DateTime.Now;        

    try
    {
        string query = "SELECT COUNT(ControlNumber) FROM Log WHERE DateChanged > #" + curTime.AddHours(-1) + "# AND User = '" + User + "' AND Log.EndStatus in ('Needs Review', 'Check Search', 'Vision Delivery', 'CA Review', '1TSI To Be Delivered');";
        OleDbCommand dbcommand = new OleDbCommand(query, conn);
        dbcommand.Connection.Open();
        dbcommand.CommandType = CommandType.Text;
        OrdersPerHour = (int?)dbcommand.ExecuteScalar();

        Console.WriteLine("Orders per hour for " + User + " is " + OrdersPerHour);            
    }
    catch (OleDbException ex)
    {

    }
    finally
    {
        conn.Close();
    }
    return OrdersPerHour;
}

采纳答案by Dimitar Dimitrov

Well you're casting OrdersPerHourto an int?

那么你正在投射OrdersPerHourint?

OrdersPerHour = (int?)dbcommand.ExecuteScalar();

Yet your method signature is int:

然而你的方法签名是int

static int OrdersPerHour(string User)

The two have to match.

两者必须匹配。



Also a quick suggestion -> Use parameters in your query, something like:

还有一个快速建议 ->在查询中使用参数,例如:

string query = "SELECT COUNT(ControlNumber) FROM Log WHERE DateChanged > ? AND User = ? AND Log.EndStatus in ('Needs Review', 'Check Search', 'Vision Delivery', 'CA Review', '1TSI To Be Delivered')";
OleDbCommand dbcommand = new OleDbCommand(query, conn);
dbcommand.Parameters.Add(curTime.AddHours(-1));
dbcommand.Parameters.Add(User);

回答by cassiorgr

Your method's return type is intand you're trying to return an int?.

您的方法的返回类型是int并且您正在尝试返回一个int?.

回答by loopedcode

You can change the last line to following (assuming you want to return 0 when there is nothing in db):

您可以将最后一行更改为以下内容(假设您想在 db 中没有任何内容时返回 0):

return OrdersPerHour == null ? 0 : OrdersPerHour.Value;

回答by Pierre-Luc Pineault

The first problem encountered with your code is the message

您的代码遇到的第一个问题是消息

Local variable OrdersPerHour might not be initialized before accessing.

局部变量 OrdersPerHour 在访问之前可能没有初始化。

It happens because in the case where your database query would throw an exception, the value might not be set to something (you have an empty catch clause).

发生这种情况是因为在您的数据库查询会抛出异常的情况下,该值可能未设置为某些内容(您有一个空的 catch 子句)。

To fix this, set the value to what you'd want to have if the query fails, which is probably 0:

要解决此问题,请将值设置为查询失败时您想要的值,这可能是0

int? OrdersPerHour = 0;

int? OrdersPerHour = 0;

Once this is fixed, now there's the error you're posting about. This happens because your method signature declares you are returning an int, but you are in fact returning a nullable int, int?, variable.

修复此问题后,现在就会出现您发布的错误。发生这种情况是因为您的方法签名声明您正在返回一个int,但实际上您正在返回一个可为空的 int, int?, 变量。

So to get the intpart of your int?, you can use the .Valueproperty:

所以要得到int你的部分int?,你可以使用.Value属性:

return OrdersPerHour.Value;

However, if you declared your OrdersPerHour to be nullat start instead of 0, the value can be null so a proper validation before returning is probably needed (Throw a more specific exception, for example).

但是,如果您将 OrdersPerHour 声明null为 start 而不是0,则该值可以为 null,因此可能需要在返回之前进行适当的验证(例如,抛出更具体的异常)。

To do so, you can use the HasValueproperty to be sure you're having a value before returning it:

为此,您可以使用该HasValue属性在返回之前确保您拥有一个值:

if (OrdersPerHour.HasValue){
    return OrdersPerHour.Value;
}
else{
    // Handle the case here
}


As a side note, since you're coding in C# it would be better if you followed C#'s conventions. Your parameter and variables should be in camelCase, not PascalCase. So Userand OrdersPerHourwould be userand ordersPerHour.

附带说明一下,由于您使用 C# 进行编码,因此如果您遵循 C# 的约定会更好。你的参数和变量应该是驼峰式的,而不是 PascalCase。所以UserandOrdersPerHour将是userand ordersPerHour

回答by tariq

this is because the return type of your method is int and OrdersPerHour is int? (nullable) , you can solve this by returning its value like below:

这是因为您的方法的返回类型是 int 而 OrdersPerHour 是 int?(nullable) ,您可以通过返回其值来解决此问题,如下所示:

return OrdersPerHour.Value

also check if its not null to avoid exception like as below:

还要检查它是否不为空以避免异常,如下所示:

if(OrdersPerHour != null)
{

    return OrdersPerHour.Value;

}
else
{

  return 0; // depends on your choice

}

but in this case you will have to return some other value in the else part or after the if part otherwise compiler will flag an error that not all paths of code return value.

但在这种情况下,您将不得不在 else 部分或 if 部分之后返回一些其他值,否则编译器将标记一个错误,即并非所有代码路径都返回值。

回答by Josh

OrdersPerHour = (int?)dbcommand.ExecuteScalar();

OrdersPerHour = (int?)dbcommand.ExecuteScalar();

This statement should be typed as, OrdersPerHour = (int)dbcommand.ExecuteScalar();

此语句应键入为, OrdersPerHour = (int)dbcommand.ExecuteScalar();

回答by FalloutBoy

Int32 OrdersPerHour = 0;
OrdersPerHour = Convert.ToInt32(dbcommand.ExecuteScalar());

回答by HoQuocThinh

simple

简单的

(i == null) ? i.Value : 0;

回答by Rubens Farias

If you're concerned with the possible nullreturn value, you can also run something like this:

如果您关心可能的null返回值,您还可以运行如下代码:

int ordersPerHour;  // can't be int? as it's different from method signature
// ... do stuff ... //
ordersPerHour = (dbcommand.ExecuteScalar() as int?).GetValueOrDefault();

This way you'll deal with the potential unexpected results and can also provide a default value to the expression, by entering .GetValueOrDefault(-1)or something more meaningful to you.

通过这种方式,您将处理潜在的意外结果,还可以通过输入.GetValueOrDefault(-1)或对您更有意义的内容为表达式提供默认值。

回答by Adem El Awity

Check the declaration of your variable. It must be like that

检查变量的声明。一定是这样

public Nullable<int> x {get; set;}
public Nullable<int> y {get; set;}
public Nullable<int> z {get { return x*y;} }

I hope it is useful for you

我希望它对你有用