
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
788
|
Chapter 13: Reflection
See Also
See the “MethodInfo Class,” “MethodBody Class,” “ReadOnlyCollection<T> Class,” and
“LocalVariableInfo Class” topics in the MSDN documentation.
13.16 Creating a Generic Type
Problem
You want to create a generic type using only the reflection APIs.
Solution
You create a generic type similarly to how a nongeneric type is created; however,
there is an extra step of creating the type arguments you want to use in creating this
generic type and binding these type arguments to the generic type’s type parameters
at construction. To do this, you will use a new method added to the
Type class called
BindGenericParameters:
public static void CreateMultiMap(Assembly asm)
{
// Get the type we want to construct.
Type typeToConstruct = asm.GetType(
"CSharpRecipes.DataStructsAndAlgorithms+MultiMap`2");
// Get the type arguments we want to construct our type with.
Type[] typeArguments = new Type[2] {Type.GetType("System.Int32"),
Type.GetType("System.String")};
// Bind these type arguments to our generic type.
Type newType = typeToConstruct.MakeGenericType(typeArguments);
// Construct our type.
DataStructsAndAlgorithms.MultiMap<int, string> mm = (
DataStructsAndAlgorithms.MultiMap<int,
string>)Activator.CreateInstance(newType);
// Test our newly constructed type.
Console.WriteLine("Count ...