将c#Null-Coalescing运算符与int一起使用

Ron*_*ald 3 c# null-coalescing-operator

我正在尝试在int上使用null-coalescing运算符.当我在字符串上使用它时它可以工作

UserProfile.Name = dr["Name"].ToString()??"";
Run Code Online (Sandbox Code Playgroud)

当我尝试在这样的int上使用它时

UserProfile.BoardID = Convert.ToInt32(dr["BoardID"])??default(int);
Run Code Online (Sandbox Code Playgroud)

我收到此错误消息

接线员'??' 不能应用于'int'和'int'类型的操作数

我找到了这篇博文,其中使用了http://davidhayden.com/blog/dave/archive/2006/07/05/NullCoalescingOperator.aspx和int数据类型.谁能说出我做错了什么?

n8w*_*wrl 7

如果dr ["BoardID"]从数据库中为NULL,我怀疑你真正要做的是将BoardID设置为0.因为如果dr ["BoardID"]为空,则Convert.ToInt32将失败.试试这个:

UserProfile.BoardID = (dr["BoardID"] is DbNull) ? 0 : Convert.ToInt32(dr["BoardID"]);
Run Code Online (Sandbox Code Playgroud)

  • +1是唯一一个真正尝试确定用户尝试做什么而不是继续关于值和引用类型的人. (2认同)

Cod*_*aos 6

An intis never null,所以应用??它是没有意义的。

实现您想要的一种方法是TryParse

int i;
if(!int.TryParse(s, out i))
{
    i = 0;
}
Run Code Online (Sandbox Code Playgroud)

或者因为你想得到0或者default(int)你可以扔掉if,因为TryParse错误情况下的输出参数已经是default(int)

int i;
int.TryParse(s, out i);
Run Code Online (Sandbox Code Playgroud)

您链接的文章int??but的左侧没有int?。这是 的快捷方式Nullable<int>null因此它支持??是有意义的。

int? count = null;    
int amount = count ?? default(int); //count is `int?` here and can be null
Run Code Online (Sandbox Code Playgroud)


Meh*_*dad 5

是的,当然......因为int不能为空.
它只有32位,所有组合代表一个有效的整数.

int?如果你想要可空性,请改用.(这是简写System.Nullable<int>.)