c Reflection calls a method example

  • 2020-06-19 11:36:08
  • OfStack

Two forms of obtaining information about a method

Reflection is an C# feature that allows users to obtain class information. Type objects map the underlying objects it represents.

In.Net, once you have an Type object, you can use the GetMethods() method to get a list of supported methods of this type. There are two forms of this method:

MethodInfo [] GetMethods()

MethodInfo [] GetMethods(BindingFlags bindingflas) : It takes a parameter with one constraint and BindingFlags is one enumeration

Enumeration member [DeclaredOnly,Instance,Public] enumeration member function is used in the compiler to use the "." symbol after your own careful observation [believe you will understand soon]

The ParameterInfo[] GetParameters() method returns a list of parameters for 1 method

The class MyClass used below, Which I have folded for easy reading!


class MyClass
    {
        int x;
        int y;
        public MyClass(int i, int j)
        {
            this.x = i;
            this.y = j;
        }
        public int Sum()
        {
            return x + y;
        }
        public bool IsBetween(int i)
        {
            if (x < i && i < y)
            {
                return true;
            }
            return false;
        }
        public void Set(int a, int b)
        {
            x = a;
            y = b;
        }
        public void Set(double a, double b)
        {
            x = (int)a;
            y = (int)b;
        }
        public void Show()
        {
            Console.WriteLine("x: " + x + "  y:  " + y);
        }
    }
MyClass

Main:


Type t = typeof(MyClass);// To obtain 1 A said MyClass Of the class Type object 
            Console.WriteLine(" Gets the name of the current member " + t.Name);
            Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
            Console.WriteLine(" Supported methods ");
            #region  The first 1 Kind of form 
            //MethodInfo[] mi = t.GetMethods();// According to Class A supported method in a class 
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            // methods GetMethods()  the  MyClass  The base class  object The methods are all shown 
            // So let's talk about   GetMethods()  The other 1 In the form of a limited display 
            #endregion
            #region  The first 2 Kind of form 
            MethodInfo[] mi = t.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public);
            #endregion
            foreach (MethodInfo m in mi)
            {
                // Return and print it out MyClass The type of a member in a class ( The return value type of the ) Extreme method name 
                Console.Write("  " + m.ReturnType.Name + "  " + m.Name + " (");//ReturnType Gets the return type of this method 
                ParameterInfo[] pi = m.GetParameters();// Gets the parameters of the method 
                for (int i = 0; i < pi.Length; i++)
                {
                    Console.Write(pi[i].ParameterType.Name + "   " + pi[i].Name);//ParameterType  Gets the parameter Type (type) 
                    if (i+1<pi.Length)
                    {
                        Console.Write(", ");
                    }

                }
                Console.WriteLine(")");
                Console.WriteLine();
            }        

            Console.ReadKey();


Invoke methods using reflection

We've discussed how to get methods supported by a type, but we're ready to get calls to methods!

The Invoke() method in the MethodInfo class provides this skill!

One form of it: object Invoke(object obj,object [] paramenters)

obj is an object reference that calls the method on the object it points to. For the static method, obj must be null.

All parameters that need to be passed to the method must be specified in the parameters array. paramenters must be null if the method does not require parameters

The Invoke() method of the base class MethodBase returns the return value of the called method

Here are some examples:

MyClass class Set() method has been changed:


public void Set(int a, int b)
        {
Console.WriteLine("Set(int,int)"); 
x = a;
y = b;
Show();
        }
        public void Set(double a, double b)
        {
Console.WriteLine("Set(double,double)");
x = (int)a;
y = (int)b;
Show();
        }


Type t = typeof(MyClass);
MyClass reflectOb = new MyClass(10, 20);
int val;
Console.WriteLine("Invoke methods in " + t.Name);// call MyClass Methods of a class 
Console.WriteLine();
MethodInfo[] mi = t.GetMethods();
foreach (MethodInfo m in mi)// Call each method 
{
    // Obtain method parameters 
    ParameterInfo[] pi = m.GetParameters();
    if (m.Name.Equals("Set",StringComparison.Ordinal)&&pi[0].ParameterType==typeof(int))
    {
        //      The specified  System.String.Compare(System.String,System.String)  and  System.String.Equals(System.Object)
        //      Method to use the region, case, and collation rules. 
        //StringComparison.Ordinal    Compare strings using ordinal collation  
        object[] obj = new object[2];
        obj[0] = 9;
        obj[1] = 18;
        m.Invoke(reflectOb, obj);
    }
    else if (m.Name.Equals("Set",StringComparison.Ordinal)&&pi[0].ParameterType==typeof(double))
    {
        object[] obj = new object[2];
        obj[0] = 1.12;
        obj[1] = 23.4;
        m.Invoke(reflectOb, obj);
    }
    else if (m.Name.Equals("Sum",StringComparison.Ordinal))
    {
        val = (int)m.Invoke(reflectOb, null);
        Console.WriteLine("Sum is : " + val);
    }
    else if (m.Name.Equals("IsBetween", StringComparison.Ordinal))
    {
        object[] obj = new object[1];
        obj[0] = 14;
        if ((bool)m.Invoke(reflectOb, obj))
        {
Console.WriteLine("14 is between x and y"); 
        }
    }
    else if (m.Name.Equals("Show",StringComparison.Ordinal))
    {
        m.Invoke(reflectOb,null);
    }
}
Main


Related articles: