c# - 将 c# 空合并运算符与 int 一起使用

标签 c# null-coalescing-operator

我正在尝试对 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/

相关文章:

c# - 检测两张图片是否相似

C# 反射按名称获取字段或属性

f# - F# 中的空合并运算符?

c# - 同一应用程序的两个实例之间的静态方法

angular - 空合并运算符 Angular 2

c# - C# 中的空合并运算符和运算符 &&

c# - 如何使用 CodeDOM 表达空合并运算符?

c# - C++ 套接字读取端读取所有连接的消息

javascript - C# 和 Javascript 中的正则表达式

c# - 如何使用C# UdpClient发送大数据?