如何通过反射判断 C# 方法是否为 async/await? [英] How can I tell if a C# method is async/await via reflection?

查看:127
本文介绍了如何通过反射判断 C# 方法是否为 async/await?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如

class Foo { public async Task Bar() { await Task.Delay(500); } }

如果我们正在反思这个类和方法,我如何确定这是否是一个实际的 async/await 方法,而不仅仅是一个恰好返回 Task 的方法?

If we are reflecting over this class and method, how can I determine if this is an actual async/await method rather than simply a method that happens to return a Task?

class Foo { public Task Bar() { return Task.Delay(500); } }

推荐答案

在我的代码副本中,async 方法的 MethodInfoCustomAttributes 属性:

In my copy of your code, the MethodInfo for the async method contains the following items in the CustomAttributes property:

  • a DebuggerStepThroughAttribute
  • a AsyncStateMachineAttribute

而普通方法的 MethodInfo 在其 CustomAttributes 属性中没有 项.

whereas the MethodInfo for the normal method contains no items in its CustomAttributes property.

看起来像 AsyncStateMachineAttribute 应该可靠地async方法上找到,而不是在标准方法上.

It seems like the AsyncStateMachineAttribute should reliably be found on an async method and not on a standard one.

事实上,该页面甚至在示例中有以下内容!

In fact, that page even has the following in the examples!

如以下示例所示,您可以确定方法是使用 Async (Visual Basic) 还是 async (C# Reference) 修饰符标记的.在示例中,IsAsyncMethod 执行以下步骤:

As the following example shows, you can determine whether a method is marked with Async (Visual Basic) or async (C# Reference) modifier. In the example, IsAsyncMethod performs the following steps:

  • 使用 Type.GetMethod 获取方法名称的 MethodInfo 对象.

  • Obtains a MethodInfo object for the method name by using Type.GetMethod.

使用 GetType 运算符 (Visual Basic) 或 typeof(C# 参考)获取属性的 Type 对象.

Obtains a Type object for the attribute by using GetType Operator (Visual Basic) or typeof (C# Reference).

使用 MethodInfo.GetCustomAttribute 获取方法和属性类型的属性对象.如果 GetCustomAttribute 返回 Nothing (Visual Basic) 或 null (C#),则该方法不包含该属性.

Obtains an attribute object for the method and attribute type by using MethodInfo.GetCustomAttribute. If GetCustomAttribute returns Nothing (Visual Basic) or null (C#), the method doesn't contain the attribute.

private static bool IsAsyncMethod(Type classType, string methodName)
{
    // Obtain the method with the specified name.
    MethodInfo method = classType.GetMethod(methodName);

    Type attType = typeof(AsyncStateMachineAttribute);

    // Obtain the custom attribute for the method. 
    // The value returned contains the StateMachineType property. 
    // Null is returned if the attribute isn't present for the method. 
    var attrib = (AsyncStateMachineAttribute)method.GetCustomAttribute(attType);

    return (attrib != null);
}

这篇关于如何通过反射判断 C# 方法是否为 async/await?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆