Prev | Current Page 195 | Next

Jon Skeet

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

Invoke(null, null);
First we retrieve the generic method definition, and then we make a constructed
generic method using MakeGenericMethod. As with types, we could go the other way if
we wanted to??”but unlike Type.GetType, there is no way of specifying a constructed
method in the GetMethod call. The framework also has a problem if there are methods
that are overloaded purely by number of type parameters??”there are no methods
in Type that allow you to specify the number of type parameters, so instead you??™d have
to call Type.GetMethods and find the right one by looking through all the methods.
After retrieving the constructed method, we invoke it. The arguments in this example
are both null as we??™re invoking a static method that doesn??™t take any ???normal???
parameters. The output is System.String, as we??™d expect.
Note that the methods retrieved from generic type definitions cannot be invoked
directly??”instead, you must get the method from a constructed type. This applies to
both generic methods and nongeneric methods.
Again, more methods and properties are available on MethodInfo, and IsGeneric-
Method is a good starting point in MSDN. Hopefully the information in this section will
have been enough to get you going, though??”and to point out some of the added complexities
you might not have otherwise anticipated when first starting to access generic
types and methods with reflection.


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