Don*_*ong 6 c# reflection methodinfo
这是我的测试代码:扩展方法GetInstructions来自此处:https : //gist.github.com/jbevain/104001
using System;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
typeof(TestClass)
.GetMethods()
.Where(method => method.Name == "Say" || method.Name == "Hello")
.ToList()
.ForEach(method =>
{
var calls = method.GetInstructions()
.Select(x => x.Operand as MethodInfo)
.Where(x => x != null)
.ToList();
Console.WriteLine(method);
calls.ForEach(call =>
{
Console.WriteLine($"\t{call}");
call.GetGenericArguments().ToList().ForEach(arg => Console.WriteLine($"\t\t{arg.FullName}"));
});
});
Console.ReadLine();
}
}
class TestClass
{
public async Task Say()
{
await HelloWorld.Say<IFoo>();
HelloWorld.Hello<IBar>();
}
public void Hello()
{
HelloWorld.Say<IFoo>().RunSynchronously();
HelloWorld.Hello<IBar>();
}
}
class HelloWorld
{
public static async Task Say<T>() where T : IBase
{
await Task.Run(() => Console.WriteLine($"Hello from {typeof(T)}.")).ConfigureAwait(false);
}
public static void Hello<T>() where T : IBase
{
Console.WriteLine($"Hello from {typeof(T)}.");
}
}
interface IBase
{
Task Hello();
}
interface IFoo : IBase
{
}
interface IBar : IBase
{
}
}
Run Code Online (Sandbox Code Playgroud)
运行结果如下图所示:
System.Threading.Tasks.Task Say()
System.Runtime.CompilerServices.AsyncTaskMethodBuilder Create()
Void Start[<Say>d__0](<Say>d__0 ByRef)
ConsoleApp1.TestClass+<Say>d__0
System.Threading.Tasks.Task get_Task()
Void Hello()
System.Threading.Tasks.Task Say[IFoo]()
ConsoleApp1.IFoo
Void RunSynchronously()
Void Hello[IBar]()
ConsoleApp1.IBar
Run Code Online (Sandbox Code Playgroud)
NON-ASYNC调用具有正确的泛型参数,但ASYNC调用却没有。
我的问题是:ASYNC调用的通用参数存储在哪里?
非常感谢。
该async方法是不那么容易。
C#编译器将根据async方法生成综合状态机。因此,TestClass.Say方法的主体将被编译器完全覆盖。如果您想深入了解异步状态机制,可以阅读这篇出色的博客文章。
回到您的问题。
编译器将用以下内容替换方法主体:
<Say>d__0 stateMachine = new <Say>d__0();
stateMachine.<>4__this = this;
stateMachine.<>t__builder = AsyncTaskMethodBuilder.Create();
stateMachine.<>1__state = -1;
AsyncTaskMethodBuilder <>t__builder = stateMachine.<>t__builder;
<>t__builder.Start(ref stateMachine);
return stateMachine.<>t__builder.Task;
Run Code Online (Sandbox Code Playgroud)
<Say>d__0在这段代码中,是编译器生成的类型。它的名称中包含特殊字符,以防止您能够在代码中使用此类型。
<Say>d__0是一个IAsyncStateMachine实现。主要逻辑包含在其MoveNext方法中。
它看起来类似于:
TaskAwaiter awaiter;
if (state != 0)
{
awaiter = HelloWorld.Say<IFoo>().GetAwaiter();
if (!awaiter.IsCompleted)
{
// ...
builder.AwaitUnsafeOnCompleted(ref awaiter, ref stateMachine);
return;
}
}
else
{
awaiter = this.awaiter;
state = -1;
}
awaiter.GetResult();
HelloWorld.Hello<IBar>();
Run Code Online (Sandbox Code Playgroud)
请注意,您的HelloWorld.Say<IFoo>()呼叫现在已在此方法中,而不是原始位置TestClass.Say。
因此,要从您的方法中获取通用类型信息,您将需要检查MoveNext状态机方法而不是原始方法TestClass.Say。在此处搜索通话说明。
像这样:
Type asyncStateMachine =
typeof(TestClass)
.GetNestedTypes(BindingFlags.NonPublic)
.FirstOrDefault(
t => t.GetCustomAttribute<CompilerGeneratedAttribute>() != null
&& typeof(IAsyncStateMachine).IsAssignableFrom(t));
MethodInfo method = asyncStateMachine.GetMethod(
nameof(IAsyncStateMachine.MoveNext),
BindingFlags.NonPublic | BindingFlags.Instance);
List<MethodInfo> calls = method.GetInstructions()
.Select(x => x.Operand as MethodInfo)
.Where(x => x != null)
.ToList();
// etc
Run Code Online (Sandbox Code Playgroud)
输出:
Void MoveNext()
System.Threading.Tasks.Task Say[IFoo]()
ConsoleApp1.IFoo
System.Runtime.CompilerServices.TaskAwaiter GetAwaiter()
Boolean get_IsCompleted()
Void AwaitUnsafeOnCompleted[TaskAwaiter,<Say>d__0](System.Runtime.CompilerServices.TaskAwaiter ByRef, <Say>d__0 ByRef)
System.Runtime.CompilerServices.TaskAwaiter
ConsoleApp1.TestClass+<Say>d__0
Void GetResult()
Void Hello[IBar]()
ConsoleApp1.IBar
Void SetException(System.Exception)
Void SetResult()
Run Code Online (Sandbox Code Playgroud)
请注意,此代码取决于当前的IAsyncStatMachine实现内部。如果C#编译器更改了该内部实现,则此代码可能会中断。