【发布时间】:2019-01-07 10:00:22
【问题描述】:
我有一个要求,我需要知道类 (ApiController) 的名称,该类有一个方法 (GetMethod),该方法由另一个方法 (OtherMethod) 来自不同的类 (OtherClass)。
为了帮助解释这一点,我希望下面的伪代码 sn-ps 有所帮助。
ApiController.cs
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*/)
}
}
我的尝试:
- 我查看了How can I find the method that called the current method?,答案将为我提供调用方法 (OtherMethod) 但不是具有该方法的类 (ApiController)李>
- 我尝试了
[CallerMemberName]和使用StackTrace属性,但这些并没有让我知道方法的类名
【问题讨论】:
-
StackFrame.GetMethod()可能对你有用。 -
如果你知道如何获取方法,你也知道哪个类有方法。返回的信息不仅仅是一个方法的名字,它是方法的所有信息,包括类
-
new StackTrace().GetFrame(1).GetMethod().DeclaringType.FullName -
如果您只是使用它来打印名称,就像您的示例一样,那么它可能没问题。如果您要根据得到的答案应用任何逻辑,我会认真建议您重新审视您的设计。根据调用堆栈的确切形状神奇地改变其行为的方法非常令人困惑。 (即想象一下,如果
ApiController有某种形式的辅助类并将对OtherMethod的调用转移到辅助类中会发生什么) -
请给minimal reproducible example(下次)。
标签: c#