In 3 minutes, What is Reflection?

前端 未结 12 1187
广开言路
广开言路 2020-12-02 10:33

Many .Net interview question lists (including the good ones) contain the question: \"What is Reflection?\". I was recently asked to answer this in the context of a 5 questio

12条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-02 11:29

    By using Reflection in C#, one is able to find out details of an object, method, and create objects and invoke methods at runtime.

    using System;
    using System.Reflection;
    
    public class MyClass
    {
       public virtual int AddNumb(int numb1,int numb2)
       {
         int result = numb1 + numb2;
         return result;
       }
    
    }
    
    class MyMainClass
    {
      public static int Main()
      {
        // Create MyClass object
        MyClass myClassObj = new MyClass();
        // Get the Type information.
        Type myTypeObj = myClassObj.GetType();
        // Get Method Information.
        MethodInfo myMethodInfo = myTypeObj.GetMethod("AddNumb");
        object[] mParam = new object[] {5, 10};
        // Get and display the Invoke method.
        Console.Write("\nFirst method - " + myTypeObj.FullName + " returns " +  
                             myMethodInfo.Invoke(myClassObj, mParam) + "\n");
        return 0;
      }
    }
    

    below code will get the type information:

    Type myTypeObj = Type.GetType("MyClass");
    

    The code snippet below will get the method's information

    Methodinfo myMethodInfo = myTypeObj.GetMethod("AddNumb"); 
    

    The following code snippet will invoke the AddNumb method:

    myMethodInfo.Invoke(myClassObj, mParam);
    

提交回复
热议问题