2012-03-11 54 views
1

我有一个方法。我想检查一个条件,并且如果我的条件结果是真的抛出新的异常,则返回 。 我需要为消息异常的方法的名称。例如:如何获取方法的名称方法

public void MyMethod(Notifier not) 
{ 
    if(not.HasValue()) 
     throw new Exception("MyMethod_name : " + not.Value); 
} 

如何在方法中获取方法的名称?

+2

可能重复[从C#中的调用函数获取调用函数名称](http://stackoverflow.com/questions/1310145/get-calling-function-name-from-called-function -in-c-sharp) – 2012-03-11 05:03:49

+0

另请参阅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

+0

如果您使用.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

回答

1

这种方法避免了堆栈问题:

public void MyMethod(Notifier not) 
{ 
    if(not.HasValue()) 
    { 
     string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name; 
     throw new Exception(methodName + ": " + not.Value); 
    } 
} 

[但请注意,有时可能会出现意想不到的结果:比如,小的方法或属性往往是内联在发布版本,在这种情况下,结果将是调用者的方法名称。]

0
public void MyMethod(Notifier not) 
{ 
    StackFrame stackFrame = new StackFrame(); 
    MethodBase methodBase = stackFrame.GetMethod(); 

    if(not.HasValue()) 
     throw new Exception("MyMethod_name : " + methodBase.Name); 
} 
0

使用Reflection可以获得方法名称.....通过使用框架中强大的反射功能,您可以调用该方法。这涉及System.Reflection名称空间和GetMethod方法。

为了实现反思,采取这个链接引用......

http://www.dotnetperls.com/getmethod