类型擦除:Java与C# [英] Type erasure: Java vs C#

查看:74
本文介绍了类型擦除:Java与C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
C#与Java泛型

Java 使用类型擦除,而 C#在运行时保留类型信息,这种设计在语言行为上的实际区别是什么?

Java use Type erasure while C# keep type information at runtime, what are the practical difference in the behaviors of the language from this design?

推荐答案

类型擦除存在很多问题.它带回了难忘的回忆.我从1.6开始就没有使用Java,所以可能已经过时了,但是我记得一些事情:

There are a lot of issues with type erasure. It brings back bad memories. I haven't used Java since 1.6, so this may be out of date, but some things I remember:

  1. 您无法创建新的T(或执行任何需要了解T实际是什么类型的操作)
  2. 通用列表无法创建T的数组
  3. 您不能在Java泛型中使用int,float等
  1. You can't create a new T (or do anything that requires knowing what type T actually is)
  2. Generic lists can't create an array of T
  3. You can't use int, float, etc in generics with Java
  1. 这对性能和内存有影响,因为您始终必须使用堆版本(整数等)

  • 您不能使用两个不同的T来实现通用接口,例如 class c实现IComparable< MyClass>,IComparable< MyOtherClass> 是不可能的.

    1. 实际上,您不能重载具有不同泛型类型的方法,例如通过输入 List< T1> List< T2> 等.例如, Java-如何处理构造函数中的类型擦除?
    1. More practically, you can't overload methods with different generic types, e.g. by taking in List<T1>, List<T2>, and so on. For example, Java -- How to deal with type erasure in constructors?

  • 一切都是通过铸造和拳击来完成的
  • 这篇关于类型擦除:Java与C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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