gpt4 book ai didi

c# - 如何通过反射判断 C# 方法是否为异步/等待?

转载 作者:IT王子 更新时间:2023-10-29 04:06:10 25 4
gpt4 key购买 nike

例如

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

如果我们正在反射(reflection)这个类和方法,我如何确定这是否是一个真正的异步/等待方法,而不仅仅是一个碰巧返回任务的方法?

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

最佳答案

在我的代码副本中,async 方法的 MethodInfoCustomAttributes 属性中包含以下项目:

  • DebuggerStepThroughAttribute
  • 一个AsyncStateMachineAttribute

而普通方法的 MethodInfo 在其 CustomAttributes 属性中包含 no 项。

看起来像 AsyncStateMachineAttribute should reliably be found on an async method and not on a standard one .

编辑:事实上,该页面甚至在示例中包含以下内容!

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:

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

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

  • 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# - 如何通过反射判断 C# 方法是否为异步/等待?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20350397/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com