使用PostSharp时如何在原始方法中获取方法名称?

时间:2014-03-05 18:57:31

标签: c# postsharp

我正在使用Visual Studio 2010,.NET 3.5和PostSharp 3.1.33。当我执行此代码时

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

它会打印<Send>z__OriginalMethod,但我希望它只打印Send。有可能吗? (注意:MyInterceptorAspect扩展了MethodInterceptionAspect,它运行完美,具体实现对于这个问题并不重要)

1 个答案:

答案 0 :(得分:1)

由于PostSharp在编译后更改了方法,因此一种解决方案是在编译时解决它,而不是运行时。

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

Console.WriteLine(CurrentMethod());

或者,您可以使用正则表达式搜索“受损”名称,以查找原始名称。

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