转:.NET获取当前方法名或调用此方法的方法名

Introduction

Before .NET, we were always looking for a way to log current method name in a log file for better logging. But, there were no functionalities that could have helped in this, and it was left as an uncompleted job.

But, with .NET, we could easily find out the name of the current method or parent method. This has been accomplished by StackFrame, StackTrace, and MethodBase classes in System.Diagnostics and System.Reflection namespaces.

  • StackFrame provides information about function call on stack call for current process.
  • StackTrace is a collection of StackFrame.
  • MethodBase is an abstract class containing information about current method.

Note: When an exception occurs in the method, exception object contains a reference to the StackTrace object that could be used to log the method name. But for logging a method name without an error generated, we need to read it from the stack, using StackFrame class.

In the sample, MethodBase object would reference to current function on stack call returned by StackFrame object. To get the parent method, we would use StackTrace to get parent’s StackFrame object.

Create a new console application:

Add namespaces:

using System.Diagnostics;
using System.Reflection;

[STAThread]
static void Main(string[] args)
{
    WhatsMyName();
}
// 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} ", methodBase.Name ); 
}

Note: This feature is not available in .NET Compact Framework as StackFrame class is unavailable. For that, you would need to use same old method of manually passing method name to the logging function.

http://www.codeproject.com/Articles/7964/Logging-method-name-in-NET

http://www.cnblogs.com/ndaysy/p/3297768.html

 

常用方式:

StackFrame sf = new StackFrame(1);
log.Error(sf.GetMethod().DeclareTypeName);

 

转载于:https://www.cnblogs.com/pengzhen/p/3633831.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值