获取当前运行函数及调用函数

   // function to display its name

        private static void WhatsMyName()

        {

            StackFrame stackFrame = new StackFrame();

            MethodBase methodBase = stackFrame.GetMethod();

            Console.WriteLine(methodBase.Name); // Displays “WhatsmyName”

            WhoCalledMe();

        }

        // Function to display parent function

        private static void WhoCalledMe()

        {

            StackTrace stackTrace = new StackTrace();

            StackFrame stackFrame = stackTrace.GetFrame(1);

            MethodBase methodBase = stackFrame.GetMethod();

            // Displays “WhatsmyName”,(下一行如果不写的话,会引发异常)

            Console.WriteLine("Parent Method Name {0} \n", methodBase.Name);

            CallingSequence();

        }

        //演示追踪函数堆栈,查找函数名

        private static void CallingSequence()

        {

            StackTrace st = new StackTrace(1, true);//跳过给定的帧数

            for (int i = 0; i < st.FrameCount; i++)

            {

                StackFrame sf = st.GetFrame(i);

                Console.WriteLine("Method: {0}, Return Type: {1}", sf.GetMethod(), ((MethodInfo)sf.GetMethod()).ReturnType);

            }

        }

1、返回当前方法所在的类名:
                     using System.Reflection;
 
                     sting className = MethodBase.GetCurrentMethod().ReflectedType.Name;
 
2、返回调用当前方法的方法名:
                    using System.Diagnostics;
                    using System.Reflection;
 
                   StackTrace   trace   =   new   StackTrace();   
                   MethodBase   methodName =  trace.GetFrame(1).GetMethod();
 
根据类名和函数名字符串调用相关函数

在Process.cs文件中有这样一个函数

public string a()
{
         return "1";
}

在另外一个ASPX页面中如果想通过函数名和类名调用这个函数,方法如下:

Assembly ab = Assembly.GetExecutingAssembly();//得到当前运行的程序集
Type tp = ab.GetType("Test.Process");//得到指定的类,Test为命名空间,Process为类名
MethodInfo mi = tp.GetMethod("a");//得到方法“a()”的信息
object ob = Activator.CreateInstance(tp);//对得到的tp实例化,得到对象ob
object s = mi.Invoke(ob,null);//调用ob对象的mi中的方法,null表示没有参数,如果有参数,需要传入一个object数组
Response.Write(s.ToString());//打印出函数“a()”的返回值

原文地址:https://www.cnblogs.com/yongtaiyu/p/2901366.html