Sun*_*aul 2 c# asp.net asp.net-mvc c#-3.0 c#-4.0
我想通过使用反射等来获取此方法的名称...我使用了很多东西,但我累了,请帮助我。如果该功能是同步的,那么下面的代码将正常工作。请仔细阅读下面的代码,这将清除我的问题。
// this will work fine
public void Test()
{
// This GetCurrentMethod() will you the name of current method
string CurrentMethodName = GetCurrentMethod();
// output will be CurrentMethodName = Test
}
// this will not work
public async Task<int> GETNumber(long ID)
{
// This GetCurrentMethod() will you the name of current method if the method is sync or not async
string CurrentMethodName = GetCurrentMethod();
return await Task.Run(() => { return 20; });
}
Run Code Online (Sandbox Code Playgroud)
此方法为我提供非异步方法的名称。但我如何获得上面的方法名称
> [MethodImpl(MethodImplOptions.NoInlining)]
> public static string GetCurrentMethod()
> {
> var stackTrace = new StackTrace();
> StackFrame stackFrame = stackTrace.GetFrame(1);
> return stackFrame.GetMethod().Name;
> }
Run Code Online (Sandbox Code Playgroud)
但此方法仅适用于非异步方法。那么如何在c#中获取当前的异步方法名称
你想要的其实是不可能的。编译器为该方法创建一个状态机async,类似的东西
public class GetNumberStateMachine : IAsyncStateMachine
{
// ....
void IAsyncStateMachine.MoveNext()
{
// here your actual code happens in steps between the
// await calls
}
}
Run Code Online (Sandbox Code Playgroud)
并将您的方法转换为类似的内容:
public async Task<int> GetNumber()
{
GetNumberStateMachin stateMachine = new GetNumberStatemachine();
stateMachine.\u003C\u003Et__builder = AsyncTaskMethodBuilder<int>.Create();
stateMachine.\u003C\u003E1__state = -1;
stateMachine.\u003C\u003Et__builder.Start<GetNumberStatemachine>(ref stateMachine);
return stateMachine.\u003C\u003Et__builder.Task;
}
Run Code Online (Sandbox Code Playgroud)
因此,在运行时调用您的GetCurrentMethod()不再是您的GetNumber()。
但是您可以通过以下方式获取调用方法的名称CallerMemberNameAttribute:
public static string GetCurrentMethod([CallingMemberName] string method = "")
{
return method;
}
public async Task<int> GetNumber(long ID)
{
int result = await Task.Run(() => { return 20; });
Console.WriteLine(GetCurrentMethod()); // prints GetNumber
return result;
}
Run Code Online (Sandbox Code Playgroud)
这甚至适用于async方法(我不确定,但我猜参数在编译时被替换)。
| 归档时间: |
|
| 查看次数: |
2906 次 |
| 最近记录: |