C#无法隐式转换类型'int?' 'int' [英] C# Cannot implicitly convert type 'int?' to 'int'
问题描述
我有这个查询:
int cid = (from c in dc.Cs
where c.id == cid
select c.clientid).FirstOrDefault();
return cid;
其中c.clientid可为空.但我收到此错误:
where c.clientid is nullable. But I receive this error:
无法隐式转换类型'int?'到"int".存在显式转换(您是否缺少演员表?)
Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)
推荐答案
好吧,int?
可以设为null
,而int
不能.这就是编译器 complains 的原因:当查询返回null
时,应将其分配给cid
的原因.如果是null
,您可以尝试提供一些默认值:
Well, int?
can be null
while int
can't. That's why the compiler complains: what should it assign to cid
when the query returns null
. You can try providing some default value in case of 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;
表示在null
情况下返回0
(请注意,您有两个可能性:1.第一项c.clientid
为null
; 2. dc.Cs
当过滤后为空),否则为int?.Value
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
这篇关于C#无法隐式转换类型'int?' 'int'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!