问题描述
请看下面的代码: -
Hi,
Please look at below code :-
using System.IO;
using System;
class Program
{
static void Main()
{
Console.WriteLine("Hello, World!");
int? i;
i = 0==1?1:(int?)null; //why here I have to cast null to int nullable
i = null; //not here
}
}
问题是评论。请解释。这很奇怪。
Question is on comments. Please explain. This is weird.
推荐答案
int? i = 0==1 ? 1 : null;
编译器尝试返回一个Value类型(1,整数,不能为null)和一个引用类型(null)并说这些类型不同,并且没有隐式转换
指定第二个值的类型时:
The compiler tries to return a Value type (1, integer, which can't be null) and a Reference type (null) and says "These aren't the same type, and there is no implicit conversion"
When you specify the type of the second value:
int? i = 0==1 ? 1 : (int?) null;
它实现了你要做的事情,因为存在从int到nullable int的隐式转换
It realises what you are trying to do because there is an implicit conversion from int to nullable int
first_expression和second_expression的类型必须相同,或者是隐含的转换必须从一种类型存在到另一种类型。
Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.
没有从null到int的隐式转换,反之亦然。但是,从int转换为nullable int,从null转换为nullable int。
There is no implicit conversion from null to int or vice versa. There is however conversion from int to nullable int and from null to nullable int too.
i = 0==1?1:null; // int vs. null - doesn't work
i = 0==1?1:(int?)null; // int vs. int? - works
i = 0==1?(int?)1:null; // int? vs. null - works as well
这篇关于为什么不在三元运算符中赋予Int nullable null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!