C#无法隐式转换类型'int?' 'int' [英] C# Cannot implicitly convert type 'int?' to 'int'

查看:402
本文介绍了C#无法隐式转换类型'int?' '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.clientidnull; 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆