是的,原则上是可能的,但不是免费的。

您需要创建一个 StackTrace,然后可以查看调用堆栈的 StackFrame 的

您可以通过使用 StackTrace来使用它,然后您可以从中获得反射类型。

StackTrace stackTrace = new StackTrace();           // get call stack
StackFrame[] stackFrames = stackTrace.GetFrames();  // get method calls (frames)


StackFrame callingFrame = stackFrames[1];
MethodInfo method = callingFrame.GetMethod();
Console.Write(method.Name);
Console.Write(method.DeclaringType.Name);
public class SomeClass
{
public void SomeMethod()
{
StackFrame frame = new StackFrame(1);
var method = frame.GetMethod();
var type = method.DeclaringType;
var name = method.Name;
}
}

现在我们假设你有另一门类似的课程:

public class Caller
{
public void Call()
{
SomeClass s = new SomeClass();
s.SomeMethod();
}
}

Name 将是“ Call”,类型将是“ Caller”。

更新: 两年后,因为我仍然得到这方面的赞成票

在.NET 4.5中,现在有一个更简单的方法可以做到这一点。

用上面的例子:

public class SomeClass
{
public void SomeMethod([CallerMemberName]string memberName = "")
{
Console.WriteLine(memberName); // Output will be the name of the calling method
}
}

实际上,这可以通过结合使用当前堆栈跟踪数据和反射来完成。

public void MyMethod()
{
StackTrace stackTrace = new System.Diagnostics.StackTrace();
StackFrame frame = stackTrace.GetFrames()[1];
MethodInfo method = frame.GetMethod();
string methodName = method.Name;
Type methodsClass = method.DeclaringType;
}

StackFrame数组上的 1索引将为您提供称为 MyMethod的方法

从技术上讲,您可以使用 StackTrace,但是这非常慢,并且不会给您您期望的答案。这是因为在发布版本期间,可能会出现删除某些方法调用的优化。因此,您无法在发行版中确定 stacktrace 是否“正确”。

实际上,在 C # 中没有任何万无一失或快速的方法可以做到这一点。您真的应该问问自己为什么需要它,以及如何构建应用程序,这样就可以在不知道调用它的方法的情况下做自己想做的事情。