java和c#中泛型的语法区别(syntax difference between generics in java and c#)

编程入门 行业动态 更新时间:2024-10-15 00:22:17
java和c#中泛型的语法区别(syntax difference between generics in java and c#)

我来自AC#背景,与c#相比,泛型如何看待java? (基本用法)

I'm coming from a c# background, how do generics look in java compared to c#? (basic usage)

最满意答案

这是一个相当大的问题,说实话 - 最大的区别不在于语法,而在于行为......在这一点上,他们真的非常不同。

我建议你阅读Sun的泛型教程和Angelika Langer的Java泛型常见问题解答 。 尽管从C#/ .NET首先尽可能地忘掉你对泛型的所有知识。 具体来说,尽管.NET泛型类型在执行时保留了类型参数,但Java泛型并不是由于类型擦除

换句话说,在C#中,您可以编写:

public class GenericType<T> { public void DisplayType() { Console.WriteLine(typeof(T)); } }

...你不能在Java中做到这一点:(

此外,.NET泛型可以具有值类型类型参数,而Java泛型不能(因此您必须使用List<Integer>而不是List<int> )。

这可能是两个最大的区别,但是从头开始学习Java泛型而不是C#中的“差异”是非常值得的。

That's a pretty huge question, to be honest - the biggest differences aren't in syntax, but in behaviour... at which point they're really, really different.

I would suggest you read through the Sun generics tutorial and Angelika Langer's Java Generics FAQ. Forget everything you know about generics from C#/.NET first though. In particular, while .NET generic types retain the type argument at execution time, Java generics don't due to type erasure.

So in other words, in C# you can write:

public class GenericType<T> { public void DisplayType() { Console.WriteLine(typeof(T)); } }

... you can't do this in Java :(

Additionally, .NET generics can have value type type arguments, whereas Java generics can't (so you have to use List<Integer> instead of List<int> for example).

Those are probably the two biggest differences, but it's well worth trying to learn Java generics from scratch instead of as a "diff" from C#.

更多推荐

本文发布于:2023-08-06 20:19:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1455776.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:语法   区别   中泛型   java   difference

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!