MethodInfoExtension.cs 1006 B

1234567891011121314151617181920212223242526272829303132
  1. using System;
  2. using System.Linq;
  3. using System.Reflection;
  4. using System.Threading.Tasks;
  5. namespace ZhonTai.Common.Extensions;
  6. public static class MethodInfoExtension
  7. {
  8. public static bool HasAttribute<T>(this MethodInfo method)
  9. {
  10. return method.GetCustomAttributes(typeof(T), false).FirstOrDefault() is T;
  11. }
  12. public static T GetAttribute<T>(this MethodInfo method) where T : Attribute
  13. {
  14. return method.GetCustomAttributes(typeof(T), false).FirstOrDefault() as T;
  15. }
  16. public static bool IsAsync(this MethodInfo method)
  17. {
  18. return method.ReturnType == typeof(Task)
  19. || (method.ReturnType.IsGenericType && method.ReturnType.GetGenericTypeDefinition() == typeof(Task<>));
  20. }
  21. internal static Type GetReturnType(this MethodInfo method)
  22. {
  23. var isAsync = method.IsAsync();
  24. var returnType = method.ReturnType;
  25. return isAsync ? (returnType.GenericTypeArguments.FirstOrDefault() ?? typeof(void)) : returnType;
  26. }
  27. }