/ Published in: C#
.net 2.0+ Generic classes make code size much smaller and casting objects (boxing) a cinch. However, currently there are some unsupported IDE options when trying to cast objects to and from generic objects that use mixed object types (inherited from a generic type specifier). Fear not, using reflection we can bypass the IDE and supply the users with strongly typed objects.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
to a generic declaration not a Type object. For example: public IList GetListFromType(Type memberType) { } This will not compile. Also as of .net 4.0, generic indexers are not supported, therefore: public T this<T>[int index] { get { object ret = MixedList[index]; return (T)ret; return null; } } Strongly Typed object returned from a collection of mixed object types only (easy filtering). To allow this we turn to reflection. We still have generic casting restrictions, so we class A { } class B : A { } Interface IListAB { int Count { get; } } class MyList<T> : List<T>, IListAB { public MyList() { } } IListAB NewListByType(Type elementType) { Type classType = Type.GetType(this.GetType().Namespace) + ".MyList`1", false); Type genClassType = classType.MakeGenericType(elementType); ConstructorInfo ctor = genClassType.GetConstructors()[0]; //get single public constructor } From this method, you are returned a strongly-typed List as an interface reference. Notice that we are looking up the class constructor by fully qualified name and the `1 after the name of the generic class. The 1 indicates how many generic type arguments are used in the class (a Dictionary<T1,T2> would have 2, and you would pass these types to the MakeGenericType() function). Using further reflection we can even see what type of generic returns this information based on the implementation of the class.