【问题标题】:C# Cannot implicitly convert type 'int?' to 'int'C# 不能隐式转换类型'int?到'int'
【发布时间】:2018-03-30 11:30:07
【问题描述】:

我有这个问题:

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

return cid;

其中 c.clientid 可以为空。但我收到此错误:

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

【问题讨论】:

  • 如果c.clientid 在第一个匹配项中是null,或者没有匹配项,您期望cid 的值是多少?
  • ... .FirstOrDefault().Value;
  • @alxem 不,它只是将编译器错误变成了运行时错误,并没有真正解决问题。
  • 如果您明确应该使用Nullable<int>,为什么首先要使用int?

标签: c# int


【解决方案1】:

好吧,int?可以是null,而int不能。这就是编译器抱怨的原因:当查询返回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.第一项c.clientid是null;2.dc.Cs当过滤后为 空),否则为 int?.Value

【讨论】:

  • @Samir Aguiar:抱歉,如果是 empty,.FirstOrDefault() 返回 null,最后是 single 默认值。在您的语法中,我们有 两个 默认值:当第一个值为 null 时,当 IEnumerable<T> 为空时。当默认为0 时会出现问题,但在默认情况下会出现问题,例如-1
猜你喜欢
  • 2013-05-23
  • 2011-12-24
  • 1970-01-01
  • 1970-01-01
  • 2021-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-12
相关资源
最近更新 更多