Wednesday, 7 July 2010

CONSTRUCTING GENERICS THROUGH REFLECTION (LIST OF MIXED TYPES EXAMPLE)

.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.

  1. The problem: Lets say I want to construct a generic object, but all I have is a Type object
  2. instance. The problem with the syntax of the IDE is that you must specify a keyword type
  3. to a generic declaration not a Type object. For example:
  4. public IList GetListFromType(Type memberType)
  5. {
  6. return new MyList<memberType>();
  7. }
  8. This will not compile.
  9. Also as of .net 4.0, generic indexers are not supported, therefore:
  10. public T this<T>[int index]
  11. {
  12. get
  13. {
  14. object ret = MixedList[index];
  15. if (ret is T)
  16. return (T)ret;
  17. return null;
  18. }
  19. }
  20. ...Will also not compile. This is somewhat annoying since we want to have a specific
  21. Strongly Typed object returned from a collection of mixed object types only (easy filtering).
  22. To allow this we turn to reflection. We still have generic casting restrictions, so we
  23. cannot cast a Dictionary<B,A> to a Dictionary<A,A> even if class B is derived from
  24. class A. The only way to fix this is through interfaces. We must return an interface
  25. that is used by the derived classed, but we should be using interfaces for common public
  26. functionality between derived classes anyway. So the solution is:
  27. class A { }
  28. class B : A { }
  29. Interface IListAB
  30. {
  31. int Count { get; }
  32. }
  33. class MyList<T> : List<T>, IListAB
  34. {
  35. public MyList()
  36. {
  37. }
  38. }
  39. IListAB NewListByType(Type elementType)
  40. {
  41. Type classType = Type.GetType(this.GetType().Namespace) + ".MyList`1", false);
  42. Type genClassType = classType.MakeGenericType(elementType);
  43. ConstructorInfo ctor = genClassType.GetConstructors()[0]; //get single public constructor
  44. return (IListAB)ctor.Invoke(new object[] {});
  45. }
  46. From this method, you are returned a strongly-typed List as an interface reference. Notice
  47. that we are looking up the class constructor by fully qualified name and the `1 after the
  48. name of the generic class. The 1 indicates how many generic type arguments are used in the
  49. class (a Dictionary<T1,T2> would have 2, and you would pass these types to the
  50. MakeGenericType() function). Using further reflection we can even see what type of generic
  51. derivation the list is a type of, or we could simply put a method in the interface that
  52. returns this information based on the implementation of the class.

No comments:

Post a Comment