// 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);
}
}
using System.Reflection;
在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()”的返回值