Prev | Current Page 194 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"

String]");
Type closedByMethod = defByName.MakeGenericType(typeof(string));
Type closedByTypeof = typeof(List);
Console.WriteLine (closedByMethod==closedByName);
Console.WriteLine (closedByName==closedByTypeof);
Type defByTypeof = typeof(List<>);
Type defByMethod = closedByName.GetGenericTypeDefinition();
Console.WriteLine (defByMethod==defByName);
Console.WriteLine (defByName==defByTypeof);
The output of listing 3.11 is just True four times, validating that however you obtain a
reference to a particular type object, there is only one such object involved.
As I mentioned earlier, there are many new methods and properties on Type,
such as GetGenericArguments, IsGenericTypeDefinition, and IsGenericType. The
documentation for IsGenericType is probably the best starting point for further
exploration.
Listing 3.11 Various ways of retrieving generic and constructed Type objects
95 Advanced generics
REFLECTING GENERIC METHODS
Generic methods have a similar (though smaller) set of additional properties and
methods. Listing 3.12 gives a brief demonstration of this, calling a generic method by
reflection.
public static void PrintTypeParameter()
{
Console.WriteLine (typeof(T));
}
...
Type type = typeof(Snippet);
MethodInfo definition = type.GetMethod("PrintTypeParameter");
MethodInfo constructed;
constructed = definition.MakeGenericMethod(typeof(string));
constructed.


Pages:
182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206