C# uses the
typeof operator to obtain such a reference for types known at compile time, and this
has been extended to encompass generic types.
There are two ways of using typeof with generic types??”one retrieves the generic
type definition (in other words, the unbound generic type) and one retrieves a particular
constructed type. To obtain the generic type definition??”that is, the type with none
of the type arguments specified??”you simply take the name of the type as it would
have been declared and remove the type parameter names, keeping any commas. To
retrieve constructed types, you specify the type arguments in the same way as you
would to declare a variable of the generic type. Listing 3.10 gives an example of both
uses. It uses a generic method so we can revisit how typeof can be used with a type
parameter, which we previously saw in listing 3.7.
9 See http://www.martinfowler.com/articles/injection.html
93 Advanced generics
static void DemonstrateTypeof
()
{
Console.WriteLine(typeof(X));
Console.WriteLine(typeof(List<>));
Console.WriteLine(typeof(Dictionary<,>));
Console.WriteLine(typeof(List));
Console.WriteLine(typeof(Dictionary));
Console.WriteLine(typeof(List));
Console.WriteLine(typeof(Dictionary));
}
...
DemonstrateTypeof();
Most of listing 3.10 is as you might naturally expect, but it??™s worth pointing out two
things.
Pages:
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202