通过反射构造泛型(混合类型列表示例)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了通过反射构造泛型(混合类型列表示例)相关的知识,希望对你有一定的参考价值。
.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.
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.
以上是关于通过反射构造泛型(混合类型列表示例)的主要内容,如果未能解决你的问题,请参考以下文章