如何获取包含称为当前方法的方法的类的名称? [英] How to get the name of the class which contains the method which called the current method?
问题描述
我有一个要求,我需要知道类的名称( ApiController ),该类具有一个方法( GetMethod ),该方法由另一个方法(>
I have a requirement where I need to know the name of the class (ApiController) which has a method (GetMethod) which is called by another method (OtherMethod) from a different class (OtherClass).
为帮助解释这一点,希望下面的伪代码片段有所帮助.
To help explain this, I hope the below pseudo-code snippets help.
public class ApiController
{
public void GetMethod()
{
OtherMethod();
}
}
OtherClass.cs
public class OtherClass()
{
public void OtherMethod()
{
Console.WriteLine(/*I want to get the value 'ApiController' to print out*/)
}
}
我尝试过的事情:
- 我查看了如何找到调用当前方法的方法?答案会帮助我调用方法( OtherMethod ),但没有调用该方法的类( ApiController )
- 我尝试了
[CallerMemberName]
并使用了StackTrace
属性,但是这些不能让我知道方法的类名
- I've looked at How can I find the method that called the current method? and the answers will get me the calling method (OtherMethod) but not the class (ApiController) which has that method
- I tried
[CallerMemberName]
and usingStackTrace
properties but these don't get me the method's class name
推荐答案
using System.Diagnostics;
var className = new StackFrame(1).GetMethod().DeclaringType.Name;
转到堆栈的上一级,找到方法,并从方法中获取类型.这避免了您需要创建完整的StackTrace,而这很昂贵.
Goes to the previous level of the Stack, finds the method, and gets the type from the method. This avoids you needing to create a full StackTrace, which is expensive.
如果要使用完全限定的类名,则可以使用 FullName
.
You could use FullName
if you want the fully qualified class name.
边缘案例(以突出显示以下评论中提出的问题)
fringe cases (to highlight the issues raised in comments below)
- If compilation optimizations are enabled, the calling method may be inlined, so you may not get the value you expect. (Credit: Johnbot)
async
methods get compiled into a state machine, so again, you may not get what you expect. (Credit: Phil K)
这篇关于如何获取包含称为当前方法的方法的类的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!