2014-03-05 53 views
2

我使用Visual Studio 2010,.NET 3.5和PostSharp 3.1.33。当我执行这个代码如何在原来的方法使用PostSharp时获取方法的名称?

[MyInterceptorAspect] 
public void Send(string msg) 
{ 
    Console.WriteLine(MethodBase.GetCurrentMethod().Name); 
} 

它打印<Send>z__OriginalMethod,但我希望它仅打印Send。它有可能吗? (注意:MyInterceptorAspect扩展了MethodInterceptionAspect,它的工作原理完美无缺,具体实现对于这个问题并不重要)

+0

这是有帮助吗? http://stackoverflow.com/questions/2652460/c-sharp-how-to-get-the-name-of-the-current-method-from-code –

+0

@ Ron.B.I TNX,那种。我不得不使用'新的StackTrace()。GetFrame(4).GetMethod()。名称',这让我感觉有点不舒服,因为这个魔术数字。帧1,帧2和帧3指的是一些PostSharp的方法。 –

回答

1

由于PostSharp在编译完成后改变了你的方法,一种解决方案是在编译时解析它,而不是运行时。

string CurrentMethod([CallerMemberName] string caller = null) 
{ 
    return caller; 
} 

Console.WriteLine(CurrentMethod()); 

或者,您可以使用正则表达式搜索'mangled'名称,以找到原始名称。

string GetOriginalName(string mangled) 
{ 
    return new Regex(@"\w+").Match(mangled).Value; 
} 
+0

这是好的,但不幸的是我使用.NET 3.5(不4.5)和VS2010 ... –

+0

Hurk,没有看到。让我发布一个可以使用的正则表达式。 –

+0

工程像魅力,我接受它。谢谢肯德尔! –