- 创建被调用的类:
using System;
using System.Diagnostics;
using System.Reflection;namespace Test
{public class Util{public void GetName(){Console.WriteLine("被调用者信息:");Type t = GetType();Console.WriteLine(t.Name);Console.WriteLine(t.FullName);StackTrace stackTrace = new StackTrace(true);MethodBase methodBase = stackTrace.GetFrame(1).GetMethod();Console.WriteLine(MethodBase.GetCurrentMethod().DeclaringType.Namespace);Console.WriteLine(MethodBase.GetCurrentMethod().DeclaringType.FullName);Console.WriteLine(MethodBase.GetCurrentMethod().Name);Console.WriteLine("\n调用者信息:");Console.WriteLine(methodBase.DeclaringType.Namespace);Console.WriteLine(methodBase.DeclaringType.Name);Console.WriteLine(methodBase.Name);}}
}
- 创建调用者,也就是Main函数
using System;
using Test;namespace TestCSharp
{internal class Program{static void Main(string[] args){var u = new Util();u.GetName();Console.ReadLine();}}
}
- 输出结果
被调用者信息:
Util
Test.Util
Test
Test.Util
GetName调用者信息:
TestCSharp
Program
Main
参考:
https://blog.csdn.net/weixin_45581482/article/details/117032083