http://www.jprl.com/Blog/archive/development/2007/Aug-31.html
雖然很舊的文章,但是很詳細的比較了C#和Java泛型的差異
最近在看Essential C# 6這本書,第11章(C# 7是在第12章)有提到Java和C#泛型機制的不同。搜尋了一些資料,小弟我大致整理如下,歡迎先進補充指正,謝謝
JDK 5加入泛型,為了避免修改JVM規格影響向下相容,是在編譯器實作泛型(不是在JVM實作),另外Java的泛型不支援Primitive Type(等同C#的Value Type)
Java採用Code Sharing實作,對每一個泛型類或泛型方法只會生成一份object code(byte code),Java compiler透過type erasure實作,也導致無法在runtime時期取得泛型類或泛型方法的實際型別
C#和C++ Template採用Code Specialization實作,對每一個泛型類或泛型方法都會產生一份object code
C# 2.0加入泛型,.NET是在CLI(common language implementation)加入泛型支援,性能較好,且可以在runtime時期取得泛型類或泛型方法的實際型別資訊
參考資料:
Java魔法堂:解讀基於Type Erasure的泛型
https://www.cnblogs.com/fsjohnhuang/p/4288614.html
聊聊Java泛型類型擦除及Flink類型暗示(type hint)機制
https://www.jianshu.com/p/cfb8c1386f69
Type Erasure
https://docs.oracle.com/javase/tutorial/java/generics/erasure.html
https://stackoverflow.com/questions/355060/c-sharp-vs-java-generics
https://stackoverflow.com/questions/31693/what-are-the-differences-between-generics-in-c-sharp-and-java-and-templates-i
C# vs Java : Generics
http://toddgerspacher.blogspot.com/2017/07/c-vs-java-generics.html
Generics in Java
https://en.wikipedia.org/wiki/Generics_in_Java#Problems_with_type_erasure
Generics in the Run Time (C# Programming Guide)
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/generics-in-the-run-time
.NET Column: Introducing Generics in the CLR
https://docs.microsoft.com/en-us/archive/msdn-magazine/2003/september/net-column-introducing-generics-in-the-clr
Finally, the research group at Microsoft has modified a version of the shared source common language implementation (CLI), code-named "Rotor," to include generics support.
https://dotnetfiddle.net/MEK7FM
沒有留言:
張貼留言