自动装箱和拆箱在 Java 和 C# 中的行为是否不同
我正在手动将代码从 Java (1.6) 转换为 C#,并发现基元(int 和 double)的行为存在一些困难。在 C# 中,似乎几乎所有转换都会自动发生
List<double> list1 = new List<double>(); // legal, C#
double d0 = 3.0;
list1.Add(d0); // legal, C#
Double dd = 2.3f; // legal, C#
list1.Add(dd); // legal, C#
List<Double> list2 = new List<Double>(); // legal, C#
double d1 = 3.0;
list2.Add(d1); // legal, C#
list2.Add(2.0); // legal, C#
double d2 = list2.get(0); // legal, C#
,但在 Java 中,只允许进行一些转换,
List<double> list1 = new ArrayList<double>(); // illegal, Java
List<Double> list2 = new ArrayList<Double>(); // legal, Java
double d1 = 3.0;
list2.add(d1); // legal, Java
list2.add(2.0); // legal, Java
double d2 = list2.get(0); // legal, Java
如果您对差异和任何潜在原理进行系统分析,我将不胜感激。
I am manually converting code from Java (1.6) to C# and finding some difficulty with the behaviour of primitives (int and double). In C# it appears that almost all conversions happen automatically
List<double> list1 = new List<double>(); // legal, C#
double d0 = 3.0;
list1.Add(d0); // legal, C#
Double dd = 2.3f; // legal, C#
list1.Add(dd); // legal, C#
List<Double> list2 = new List<Double>(); // legal, C#
double d1 = 3.0;
list2.Add(d1); // legal, C#
list2.Add(2.0); // legal, C#
double d2 = list2.get(0); // legal, C#
but in Java only some are allowed
List<double> list1 = new ArrayList<double>(); // illegal, Java
List<Double> list2 = new ArrayList<Double>(); // legal, Java
double d1 = 3.0;
list2.add(d1); // legal, Java
list2.add(2.0); // legal, Java
double d2 = list2.get(0); // legal, Java
I'd be grateful for a systematic analysis of the differences and any underlying rationale.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 C# 中,
double
和Double
完全相同(只要您没有创建自己的名为Double< 的类型) /code>,这很愚蠢)。
double
被定义为global::System.Double
的别名。因此,这里没有拳击。在java中,
Double
是一个装箱的double
,类型擦除是泛型实现的关键部分。In C#,
double
andDouble
are exactly the same thing (as long as you haven't created your own type calledDouble
, which would be stupid).double
is defined as an alias toglobal::System.Double
. As such, there is no boxing here.In java,
Double
is a boxeddouble
, with type-erasure being a key part of the generics implementation.在您的 C# 示例中,没有发生装箱或拆箱(和自动装箱)。
double
只是struct
Double
的别名。在Java中,拳击是必须的。由于类型擦除,您无法创建
List
,仅List
。在编译时,List
变为List
In your C# example there is no boxing or unboxing (and autoboxing) happening.
double
is just an alias for thestruct
Double
.In Java, the boxing is necessary. Because of type erasure, you can't create a
List<double>
, onlyList<Double>
. At compile time,List<?>
becomesList<Object>
and boxing/unboxing will need to take place so you can add a native type variable to aList<Object>
or assign a native variable to an element of the List.