gpt4 book ai didi

java - C#和Java的三元运算符的区别(?:)

转载 作者:IT老高 更新时间:2023-10-28 11:30:38 24 4
gpt4 key购买 nike

我是 C# 新手,我只是遇到了一个问题。在处理三元运算符(?:)时,C# 和 Java 是有区别的。

在下面的代码段中,为什么第 4 行不起作用?编译器显示错误消息 'int' 和 'string' 之间没有隐式转换。第 5 行也不行。两个 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# 中缺少哪些语言功能?如果有,为什么不添加?

最佳答案

查看C# 5 语言规范第 7.14 节:条件运算符,我们可以看到以下内容:

  • If x has type X and y has type Y then

    • If an implicit conversion (§6.1) exists from X to Y, but not from Y to X, then Y is the type of the conditional expression.

    • If an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression.

    • Otherwise, no expression type can be determined, and a compile-time error occurs

换句话说:它尝试查找 x 和 y 是否可以转换为 彼此,如果不能,则会发生编译错误。在我们的例子中,intstring 没有显式或隐式转换,因此无法编译。

对比 Java 7 Language Specification section 15.25: Conditional Operator :

  • If the second and third operands have the same type (which may be the null type), then that is the type of the conditional expression. (NO)
  • If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T. (NO)
  • If one of the second and third operands is of the null type and the type of the other is a reference type, then the type of the conditional expression is that reference type. (NO)
  • Otherwise, if the second and third operands have types that are convertible (§5.1.8) to numeric types, then there are several cases: (NO)
  • Otherwise, the second and third operands are of types S1 and S2 respectively. Let T1 be the type that results from applying boxing conversion to S1, and let T2 be the type that results from applying boxing conversion to S2.
    The type of the conditional expression is the result of applying capture conversion (§5.1.10) to lub(T1, T2) (§15.12.2.7). (YES)

然后,查看 section 15.12.2.7. Inferring Type Arguments Based on Actual Arguments我们可以看到它试图找到一个共同的祖先,该祖先将用作用于调用的类型,该调用将其与 Object 结合。 Object is 是一个可接受的参数,因此调用将起作用。

关于java - C#和Java的三元运算符的区别(?:),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35230846/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com