繁体   English   中英

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 可以为空。 但我收到此错误:

不能隐式转换类型“int?” 到'int'。 存在显式转换(您是否缺少演员表?)

嗯,内部int? 可以nullint不能 这就是编译器抱怨的原因:当查询返回null时,它应该分配给cid什么。 您可以尝试在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. 第 1 项c.clientidnull ;2. dc.Cs过滤时为)和int?.Value否则

暂无
暂无

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

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