I have a class which has some properties of type List<float>
, List<int>
etc. Now I am quering the properties of this class through reflection so that I get a list of PropertyInfo
.
I want to filter the types which are of type List<>
. But the comparison
propertyInfo.PropertyType == typeof(List<>)
fails.
I can get around this by comparing the names, i.e., the following comparison works:
propertyInfo.PropertyType.Name == typeof(List<>).Name
I think there should be a better way to compare the Generic types. Any clues?
To compare generic types in Java, use the compareTo method.
To enable two objects of a generic type parameter to be compared, they must implement the IComparable or IComparable<T>, and/or IEquatable<T> interfaces. Both versions of IComparable define the CompareTo() method and IEquatable<T> defines the Equals() method.
You need to specify that the type E has a compareTo method, that is the contract of the interface Comparable<T> , then this could be written as: public static <E extends Comparable<E>> void inspectArray( E[] inputArray) { ... } E extends Comparable<E> .
Use the IsGenericType property to determine whether the type is generic, and use the IsGenericTypeDefinition property to determine whether the type is a generic type definition. Get an array that contains the generic type arguments, using the GetGenericArguments method.
You can use:
Type type = propertyInfo.PropertyType; if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With