/// <summary> /// Invoke an Extension method that is void. /// </summary> /// <param name="extMethodInfo"></param> /// <param name="extMethodParams"></param> public void Invoke(IExtMethodInfo extMethodInfo, params object[] extMethodParams) { if (string.IsNullOrWhiteSpace(extMethodInfo.MethodName)) { throw new ArgumentException($"{nameof(extMethodInfo.MethodName)} is empty"); } if (extMethodParams.Length < 1) { throw new TargetParameterCountException($"Invoke Extension method {extMethodInfo.MethodName}() must provide at least the extended type parameter!"); } if (extMethodInfo.ExtendedType == null) { Invoke(extMethodInfo.MethodName, extMethodParams); return; } var targetExtMethods = ExtensionLibAssembly.GetExtensionMethods(extMethodInfo); var methodInfos = targetExtMethods as MethodInfo[] ?? targetExtMethods.ToArray(); if (!methodInfos.Any()) { throw new MissingMethodException(extMethodInfo.MethodName); } methodInfos.First().Invoke(null, extMethodParams); }
/// <summary> /// Invoke an Extension method that has return type. /// </summary> /// <typeparam name="TReturn">The return type of extension method.</typeparam> /// <param name="extMethodInfo">The <see cref="IExtMethodInfo"/> object contains target extension method information.</param> /// <param name="extMethodParams">Parameters that needs to invoke the extension method.</param> /// <returns></returns> public TReturn Invoke <TReturn>(IExtMethodInfo extMethodInfo, params object[] extMethodParams) { if (string.IsNullOrWhiteSpace(extMethodInfo.MethodName)) { throw new ArgumentException($"{nameof(extMethodInfo.MethodName)} is empty"); } if (extMethodParams.Length < 1) { throw new TargetParameterCountException($"Invoke Extension method {extMethodInfo.MethodName}() must provide at least the extended type parameter!"); } if (extMethodInfo.ExtendedType == null) { return(Invoke <TReturn>(extMethodInfo.MethodName, extMethodParams)); } var targetExtMethods = ExtensionLibAssembly.GetExtensionMethods(extMethodInfo); var methodInfos = targetExtMethods as MethodInfo[] ?? targetExtMethods.ToArray(); if (!methodInfos.Any()) { throw new MissingMethodException(extMethodInfo.MethodName); } object invokeResult = null; Exception notMatchRunEx = null; foreach (var methodInfo in methodInfos.Where(x => x.GetParameters().Length == extMethodParams.Length)) { try { invokeResult = methodInfo.Invoke(null, extMethodParams); notMatchRunEx = null; break; } catch (ArgumentException ex) { notMatchRunEx = ex; } catch (TargetInvocationException ex) { if (ex.InnerException != null) { throw ex.InnerException; } throw; } } if (notMatchRunEx != null) { throw notMatchRunEx; } if (invokeResult == null) { return(default);
public static IEnumerable <MethodInfo> GetExtensionMethods(this Assembly assembly, IExtMethodInfo extMethodInfo) { return(GetExtensionMethods(assembly, extMethodInfo.ExtendedType, extMethodInfo.MethodName)); }