[英]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 .可以为
null
而int
不能。 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.clientid
为null
;2. dc.Cs
过滤时为空)和int?.Value
否则
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.