做自动装箱和拆箱行为不同Java和C# [英] Do autoboxing and unboxing behave differently in Java and C#

查看:158
本文介绍了做自动装箱和拆箱行为不同Java和C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我手动从Java(1.6)代码转换到C#和发现一些困难的原语(int和double)的行为。在C#中出现,几乎所有的转换发生自动

 列表<双> list1的=新的List<双>(); //合法,C#
双D0 = 3.0;
list1.Add(D0); //合法,C#
双击DD = 2.3f; //合法,C#
list1.Add(DD); //合法,C#
名单,LT;双>列表2 =新的List<双>(); //合法,C#
双D1 = 3.0;
list2.Add(D1); //合法,C#
list2.Add(2.0); //合法,C#
双D2 = list2.get(0); //合法,C#



但在Java只有一些被允许

 列表<双> list1的=新的ArrayList<双>(); //非法的,Java的
名单,LT;双>列表2 =新的ArrayList<双>(); //合法,爪哇
双D1 = 3.0;
list2.add(D1); //合法,爪哇
list2.add(2.0); //合法,爪哇
双D2 = list2.get(0); //合法,爪哇



我会为差异的系统的分析和任何理论基础感谢


解决方案

在你的C#示例没有拳击或拆箱(和自动装箱)发生。 双击仅仅是为结构 双击。<别名/ p>

在Java中,拳击是必要的。由于类型擦除的,你不能创建一个列表<双> ,只列表与LT;双> 。在编译时,列表<> 变成列表<对象> 和拳击/拆箱将需要采取的地方,以便您可以在本机类型变量添加到列表<对象> 或分配到列表中的一个元素的本地变量


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.

解决方案

In your C# example there is no boxing or unboxing (and autoboxing) happening. double is just an alias for the struct Double.

In Java, the boxing is necessary. Because of type erasure, you can't create a List<double>, only 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.

这篇关于做自动装箱和拆箱行为不同Java和C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆