December 2007
Intermediate to advanced
896 pages
19h 57m
English
You want to create a generic type using only the reflection APIs.
You create a generic type similarly to how a nongeneric type is created; however, there is an extra step to create 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 = {typeof(int), typeof(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 == " + mm.Count);
mm.Add(1, "test1");
Console.WriteLine("Count == " + mm.Count);
}The code to test the CreateMultiMap method is shown here:
public static void TestCreateMultiMap()
{
Assembly asm = Assembly.LoadFrom("C:\\CSharp Recipes 2nd Edition" +
"\\Code\\CSharpRecipes\\bin\\Debug\\CSharpRecipes.exe");
CreateMultiMap(asm);
}The output of this method is shown here:
Count == 0 Count == 1
Type ...
Read now
Unlock full access