简体   繁体   English

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

[英]C# Cannot implicitly convert type 'int?' to 'int'

I have this query:我有这个查询:

int cid =  (from c in dc.Cs
                where c.id == cid
                select c.clientid).FirstOrDefault();

return cid;

where c.clientid is nullable.其中 c.clientid 可以为空。 But I receive this error:但我收到此错误:

Cannot implicitly convert type 'int?'不能隐式转换类型“int?” to 'int'.到'int'。 An explicit conversion exists (are you missing a cast?)存在显式转换(您是否缺少演员表?)

Well, int?嗯,内部int? can be null while int can't .可以nullint不能 That's why the compiler complains : what should it assign to cid when the query returns null .这就是编译器抱怨的原因:当查询返回null时,它应该分配给cid什么。 You can try providing some default value in case of null :您可以尝试在null情况下提供一些默认值

int cid = (  from c in dc.Cs
            where c.id == cid
           select c.clientid)
  .FirstOrDefault() ?? 0; //TODO: put the right default value instead of 0

return cid;

which means return 0 in case of null (please, notice that you have two possibilities: 1. 1st item c.clientid is null ; 2. dc.Cs when filtered is empty ) and int?.Value otherwise这意味着在null情况下返回0 (请注意,您有两种可能性:1. 第 1 项c.clientidnull ;2. dc.Cs过滤时为)和int?.Value否则

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM