如何获取包含称为当前方法的方法的类的名称? [英] How to get the name of the class which contains the method which called the current method?

查看:40
本文介绍了如何获取包含称为当前方法的方法的类的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要求,我需要知道类的名称( ApiController ),该类具有一个方法( GetMethod ),该方法由另一个方法(> )来自其他类( OtherClass ).

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 using StackTrace 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)

  1. 如果启用了编译优化,则可能内联调用方法,因此您可能无法获得期望的值.(来源: Johnbot )
  2. async 方法被编译到状态机中,因此同样,您可能无法获得期望的结果.(来源: Phil K )
  1. If compilation optimizations are enabled, the calling method may be inlined, so you may not get the value you expect. (Credit: Johnbot)
  2. async methods get compiled into a state machine, so again, you may not get what you expect. (Credit: Phil K)

这篇关于如何获取包含称为当前方法的方法的类的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆