1、使用特性[CallerMemberName]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1
{
internal class Program
{
public static void Info(
string message,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
{
Console.WriteLine("信息为: " + message);
Console.WriteLine("方法名称: " + memberName);
Console.WriteLine("源文件地址: " + sourceFilePath);
Console.WriteLine("方法使用所在行号: " + sourceLineNumber);
}
static void Main(string[] args)
{
Info("****");
Console.ReadKey();
}
}
}
2、在某一方法体内,可以如下直接查看哪个函数调用的当前方法。
StackFrame frame = new StackFrame(1);
MethodBase method = frame.GetMethod();