C# generics do not have type wildcards because .net generics are generics supported by CLR, while Java JVM does not support generics, but only syntax sugar, and they are converted to object types when compiled by the compiler
Type wildcards represent the parent class of generic types in java
public void test(List<Object> c) { for(int i = 0;i < c.size();i++) { System.out.println(c.get(i)); } }//Create a List<String> object List<String> strList = new ArrayList<String>(); //Calendate the previous test method test(strList);
Compile the above program, and a compilation error will occur at test(strList), which means that List<String> cannot be regarded as a subclass of List<Object>. At this time, you need to use the type wildcard, which is a?
The above List<Object> can be replaced with List<?> and then it can be compiled
public void test(List<?> c) { for(int i = 0;i < c.size();i++) { System.out.println(c.get(i)); } }List<String> can be used as a subclass of List<?>, List<?> can be used as a parent class of any List type,
What if you want to be the parent class of List<String> instead of List<int>? Write it like this List<? extends String>
In C#, this is the type of constraint
class MyClass<T, U> where T : class where U : struct {} interface IMyInterface { } class Dictionary<TKey, TVal> where TKey : IComparable, IEnumerable where TVal : IMyInterface { public void Add(TKey key, TVal val) { } }Upper limit for constrained generic wildcards in Java:
//Indicate that the T type must be the Number class or its subclass, and must implement the java.io.Serializable interface Public class Apple<T extends Number & java.io.Serializable> {}The above is the complete content of the comparison and analysis of Java generic wildcards and C# brought to you by the editor. I hope everyone will support Wulin.com~