Preface
Two methods for obtaining information about a method
Reflection is a C # function that allows users to obtain class information. The Type object maps to the underlying object;
In. Net, once the Type object is obtained, you can use the GetMethods () method to obtain the list of methods supported by this Type. The methods are in the following two forms:
MethodInfo [] GetMethods ()
MethodInfo [] GetMethods (BindingFlags bindingflas): its parameters contain some restrictions that BindingFlags is an enumeration.
Enumeration member [Instance, Public
The ParameterInfo [] GetParameters () method returns a list of parameters for a method.
The following MyClass class is used. To facilitate reading, I folded it!
MyClass (I ,. x =. y = x + IsBetween (x <I & I <Set (a, x = y = Set (a, x = (y = (Console. writeLine (+ x ++}MyClass
Main:
Type t = (MyClass); Console. writeLine (+ Console. writeLine (Console. writeLine (first form second form MethodInfo [] mi = t. getMethods (BindingFlags. declaredOnly | BindingFlags. instance | (MethodInfo m Console. write (+ m. returnType. name ++ m. name +); ParameterInfo [] pi = m. getParameters (); (I =; I <pi. length; I ++ Console. write (pi [I]. parameterType. name ++ pi [I]. name); (I + <Console. write (Console. writeLine (Console. readKey ();
Use reflection call Method
We have discussed how to obtain the methods supported by a type. However, we are fully prepared to call the method!
The Invoke () method in the MethodInfo class provides this skill!
One of its forms: object Invoke (object obj, object [] paramenters)
Obj is an object reference that calls methods on the object to which it points. For static methods, obj must be null.
All parameters to be passed to the method must be specified in the parameters array. If the method does not require a parameter, paramenters must be null.
The Return Value of the called method is returned by the Invoke () method of the base MethodBase class.
See the following example:
The Set () method of the MyClass class has changed:
Set( a, Console.WriteLine( x = y = Set( a, Console.WriteLine( x = ( y = ( }
Type t = MyClass reflectOb = MyClass (, Console. writeLine (+ t. name); MethodInfo [] mi = (MethodInfo m mi) ParameterInfo [] pi = (m. name. equals (, StringComparison. ordinal) & pi []. parameterType = ([] obj = [obj [] = obj [] = (m. name. equals (, StringComparison. ordinal) & pi []. parameterType = ([] obj = [obj [] = obj [] = (m. name. equals (val = () m. invoke (reflectOb, Console. writeLine (+ (m. name. equals ([] obj = [obj [] = (Console. writeLine (m. name. equals (m. invoke (reflectOb ,}Main