<分区>
Possible Duplicate:
How can I find the method that called the current method?
我想写一个方法来获取调用方法的名称,以及包含调用方法的类的名称。
C# 反射是否可行?
标签 c# reflection
<分区>
Possible Duplicate:
How can I find the method that called the current method?
我想写一个方法来获取调用方法的名称,以及包含调用方法的类的名称。
C# 反射是否可行?
最佳答案
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”,type 将是“Caller”。
更新:两年后,我仍然对此投票
在 .NET 4.5 中,现在有一种更简单的方法来执行此操作。您可以利用 CallerMemberNameAttribute
.
继续前面的例子:
public class SomeClass
{
public void SomeMethod([CallerMemberName]string memberName = "")
{
Console.WriteLine(memberName); // Output will be the name of the calling method
}
}
关于c# - 如何使用反射获取调用方法名称和类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3095696/