为什么 ?: 运算符不能与 nullable一起使用分配?
我正在为我的数据库创建一个对象,我发现了一个奇怪的事情,我不明白:
我有一个对象应该通过 ID 引用“语言”,但这可以为空,所以我的属性是int?(Nullable
所以首先我尝试使用对象初始值设定项:
myObject = new MyObject()
{
myNullableProperty = language == null ? null : language.id;
}
但它不起作用!它告诉我 null 无法转换为 int
但如果我将它放在 if/else
结构中,我可以将 null 放入 var 中,然后将其分配给我的属性。
为什么会有这样的表现?
I'm creating an object for my database and I found a weird thing, which I don't understand:
I've an object which should reference a "language" by an ID, but this can be null, so my property is a int?(Nullable<int>)
so firstly I tried to use the object initializer:
myObject = new MyObject()
{
myNullableProperty = language == null ? null : language.id;
}
but it doesn't work! It tell me that null cannot be converted to int
But if I it in a if/else
structure, I can put null in a var and then assign it to my properties.
Why is this acting like this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以尝试将
null
转换为int?
,因为?:
运算符要求两个操作数返回相同的类型:You may try casting the
null
toint?
as the?:
operator requires both operands to return the same type:这是因为类型不匹配。您必须将 null 值转换为 int 类型。
This is because of a type mismatch. You must cast your null value to the int type.
原因是,当使用
?
运算符时,:
的左侧和右侧必须来自相同类型,且typeof(null)!= typeof(int)
所以:The reason is, when using the
?
operator the left and the right side of the:
are required to be from the same type andtypeof(null)!=typeof(int)
so:最有可能的是 null 被解释为显然不能分配给 int 的对象。您可能想使用 myNullableProperty = language == null ? (int?)null : language.id;
Most likely null is interpreted as object which obviously can't be assigned to int. You might want to use
myNullableProperty = language == null ? (int?)null : language.id;