我有一个方法。我想检查一个条件,并且如果我的条件结果是真的抛出新的异常,则返回 。 我需要为消息异常的方法的名称。例如:如何获取方法的名称方法
public void MyMethod(Notifier not)
{
if(not.HasValue())
throw new Exception("MyMethod_name : " + not.Value);
}
如何在方法中获取方法的名称?
我有一个方法。我想检查一个条件,并且如果我的条件结果是真的抛出新的异常,则返回 。 我需要为消息异常的方法的名称。例如:如何获取方法的名称方法
public void MyMethod(Notifier not)
{
if(not.HasValue())
throw new Exception("MyMethod_name : " + not.Value);
}
如何在方法中获取方法的名称?
这种方法避免了堆栈问题:
public void MyMethod(Notifier not)
{
if(not.HasValue())
{
string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
throw new Exception(methodName + ": " + not.Value);
}
}
[但请注意,有时可能会出现意想不到的结果:比如,小的方法或属性往往是内联在发布版本,在这种情况下,结果将是调用者的方法名称。]
public void MyMethod(Notifier not)
{
StackFrame stackFrame = new StackFrame();
MethodBase methodBase = stackFrame.GetMethod();
if(not.HasValue())
throw new Exception("MyMethod_name : " + methodBase.Name);
}
使用Reflection可以获得方法名称.....通过使用框架中强大的反射功能,您可以调用该方法。这涉及System.Reflection
名称空间和GetMethod
方法。
为了实现反思,采取这个链接引用......
这是你在寻找什么?
new StackFrame(1, true).GetMethod().Name
但是再次玩堆栈意味着如果滥用性能会受到打击。
OR你在找这个 - http://www.csharp-examples.net/get-method-names/
ORhttp://heifner.blogspot.co.nz/2006/12/logging-method-name-in-c.html
或看看这里不错笔记 - Get Calling function name from Called function
希望这有助于,干杯!
可能重复[从C#中的调用函数获取调用函数名称](http://stackoverflow.com/questions/1310145/get-calling-function-name-from-called-function -in-c-sharp) – 2012-03-11 05:03:49
另请参阅http://stackoverflow.com/questions/44153/can-you-use-reflection-to-find-the-name-of-the-currently-exe cuting-method – kmote 2012-03-11 05:36:58
如果您使用.net 4.5 beta +,则可以使用[CallerInformation API](http://msdn.microsoft.com/zh-cn/library/hh534540%28v=vs.110%29.aspx) 。 – 2012-03-11 07:16:01