我是一名C#新手,最近遇到了一个问题。在使用三元运算符(? :
)时,C#与Java之间存在差异。
在下面的代码片段中,为什么第四行不起作用?编译器显示一个错误消息:there is no implicit conversion between 'int' and 'string'
。第五行也不起作用。这两个List
、它们都是对象,不是吗?
int two = 2;
double six = 6.0;
Write(two > six ? two : six); //param: double
Write(two > six ? two : "6"); //param: not object
Write(two > six ? new List<int>() : new List<string>()); //param: not object
然而,同样的代码在Java中有效:
int two = 2;
double six = 6.0;
System.out.println(two > six ? two : six); //param: double
System.out.println(two > six ? two : "6"); //param: Object
System.out.println(two > six ? new ArrayList<Integer>()
: new ArrayList<String>()); //param: Object
C#缺少哪些语言特性?如果有的话,为什么没有添加?
int
不是一个对象,而是一个原始数据类型。 - Code-ApprenticeArrayList<String>
和ArrayList<Integer>
在字节码中变成了只有ArrayList
。这意味着它们在运行时看起来是完全相同的类型。显然,在C#中它们是不同的类型。 - Code-Apprentice