简体   繁体   English

自动装箱和拆箱在Java和C#中的表现不同

[英]Do autoboxing and unboxing behave differently in Java and C#

I am manually converting code from Java (1.6) to C# and finding some difficulty with the behaviour of primitives (int and double). 我手动将代码从Java(1.6)转换为C#,并发现原语(int和double)的行为有些困难。 In C# it appears that almost all conversions happen automatically 在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#

but in Java only some are allowed 但在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'd be grateful for a systematic analysis of the differences and any underlying rationale. 我很感激系统分析差异和任何潜在的理由。

In C#, double and Double are exactly the same thing (as long as you haven't created your own type called Double , which would be stupid). 在C#中, doubleDouble 完全相同 (只要你没有创建自己的类型Double ,这将是愚蠢的)。

double is defined as an alias to global::System.Double . double定义global::System.Double的别名。 As such, there is no boxing here. 因此,这里没有拳击。

In java, Double is a boxed double , with type-erasure being a key part of the generics implementation. 在java中, Double是一个盒装double精度型,其中type-erasure是泛型实现的关键部分。

In your C# example there is no boxing or unboxing (and autoboxing) happening. 在您的C#示例中,没有发生装箱或拆箱(和自动装箱)。 double is just an alias for the struct Double . double只是struct Double的别名。

In Java, the boxing is necessary. 在Java中,拳击是必要的。 Because of type erasure , you can't create a List<double> , only List<Double> . 由于类型擦除 ,您无法创建List<double> ,只能创建List<Double> At compile time, List<?> becomes List<Object> and boxing/unboxing will need to take place so you can add a native type variable to a List<Object> or assign a native variable to an element of the List. 在编译时, List<?>变为List<Object>并且需要进行装箱/取消装箱,因此您可以将本机类型变量添加到List<Object>或将本机变量分配给List的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM