【发布时间】:2011-08-05 18:14:36
【问题描述】:
是否可以在 PostError 中确定调用方法名称“Eat Pizza”? 我想我可以将“EatPizza”作为参数之一传递,但是每次方法名称更改时都需要更改(不必要的维护)。但是,我什至无法在“EatPizza”的上下文中找到方法名称“EatPizza”(使用 stacktrace、getframe、getmethod)。
public void EatPizza(Pizza p){
if(p==null){ //A arbitrary made up error
Utilities.PostError();
}
else{
p.Slices -= 1;
}
}
...
public void PostError(){
//Basically posting to database the name of the method
//Tried this, didn't work: (new StackTrace(true)).GetFrame(5).GetMethod().Name
//Is it possible to determine the calling method name "Eat Pizza" in this context?
}
当我在 StackTrace.GetFrame 中尝试不同的值(0 到 StackTrace.FrameCount-1)时,我得到以下值,而我只想要“EatPizza”:
.ctor
ThreadStart
Main
_nExecuteAssembly
RunUsersAssemblyDebugInZone
【问题讨论】:
-
你知道,抛出异常会得到堆栈跟踪,这是处理错误的推荐方法。你有什么理由不这样做?如果需要,您可以在 catch 块中调用
PostError。 -
我唯一注意到的是您将 5 传递给 GetFrame。我认为您希望当前帧为 0,前一帧为 1。但我也假设您使用它作为您尝试的事物类型的更多演示,而不是您尝试的文字代码。
-
@driis,好的,看起来不错。我现在有一个接受 Exception 参数并发布 Exception.StackTrace 的方法。我喜欢这个解决方案:)
标签: c# methods stack-trace stack-frame getmethod