As a skilled c# programmer what traps are waiting for me in the Java type arguments inference rules?
Or in other words
What are the main difference in type arguments inference for generic types bet开发者_如何学JAVAween C# and Java?
I am looking for an answer that can be read and understood in a few minutes by a skilled C# developer.
The main difference between Java & C# generics is that Java generics are enforced by the compiler, with the required cast being inserted as appropriate. The bytecode does not make reference to the generic type, this is termed 'type erasure'.
Within C# generics is present in the intermediate language, hence there is no erasure. As a result you can use reflection to read generic type parameters.
See this related question:
What are the differences between Generics in C# and Java... and Templates in C++?
One thing I found people most confused by: If a type parameter only appears in the return type, the compiler has problem infer it.
<T> T foo();
foo(); // fail, no idea what T is
That example is understandable, but the following is not
void bar(String s){..}
bar( foo() ); // fail, compiler can't infer T=String
People are quite upset that the compiler can't infer a simple case like that.
Only in 2 contexts (both "assignment conversion"), Java can infer T
String s = foo(); // ok, T=String
String doo()
{
return foo(); // ok, T=String
}
(While it compiles, it's very dangerous. How the hell does foo()
know it should return a String
? Due to type erasure it has no access to T
at runtime. Java would be better off if it didn't allow inference even in these two cases.)
Of course, when inference fail, you can always provide explicity type parameter.
精彩评论