我正在尝试对 int 使用 null 合并运算符。当我在字符串上使用它时它起作用
UserProfile.Name = dr["Name"].ToString()??"";
当我尝试像这样在 int 上使用它时
UserProfile.BoardID = Convert.ToInt32(dr["BoardID"])??default(int);
我收到这个错误信息
Operator '??' cannot be applied to operands of type 'int' and 'int'
我在使用它的地方找到了这篇博文 http://davidhayden.com/blog/dave/archive/2006/07/05/NullCoalescingOperator.aspx使用 int 数据类型。谁能告诉我我做错了什么?
最佳答案
我怀疑您真正想做的是,如果数据库中的 dr["BoardID"] 为 NULL,则将 BoardID 设置为 0。因为如果 dr["BoardID"] 为空,Convert.ToInt32 将失败。试试这个:
UserProfile.BoardID = (dr["BoardID"] is DbNull) ? 0 : Convert.ToInt32(dr["BoardID"]);
关于c# - 将 c# 空合并运算符与 int 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6627451/