using System; using System.Reflection; namespace StardewModdingAPI.Framework.Reflection { /// A method obtained through reflection. internal class ReflectedMethod : IReflectedMethod { /********* ** Fields *********/ /// The type that has the method. private readonly Type ParentType; /// The object that has the instance method, or null for a static method. private readonly object? Parent; /// The display name shown in error messages. private string DisplayName => $"{this.ParentType.FullName}::{this.MethodInfo.Name}"; /********* ** Accessors *********/ /// public MethodInfo MethodInfo { get; } /********* ** Public methods *********/ /// Construct an instance. /// The type that has the method. /// The object that has the instance method, or null for a static method. /// The reflection metadata. /// Whether the method is static. /// The or is null. /// The is null for a non-static method, or not null for a static method. public ReflectedMethod(Type parentType, object? obj, MethodInfo method, bool isStatic) { // validate if (parentType == null) throw new ArgumentNullException(nameof(parentType)); if (method == null) throw new ArgumentNullException(nameof(method)); if (isStatic && obj != null) throw new ArgumentException("A static method cannot have an object instance."); if (!isStatic && obj == null) throw new ArgumentException("A non-static method must have an object instance."); // save this.ParentType = parentType; this.Parent = obj; this.MethodInfo = method; } /// public TValue Invoke(params object?[] arguments) { // invoke method object? result; try { result = this.MethodInfo.Invoke(this.Parent, arguments); } catch (TargetParameterCountException) { throw new Exception($"Couldn't invoke the {this.DisplayName} method: it expects {this.MethodInfo.GetParameters().Length} parameters, but {arguments.Length} were provided."); } catch (Exception ex) { throw new Exception($"Couldn't invoke the {this.DisplayName} method", ex); } // cast return value try { return (TValue)result!; } catch (InvalidCastException) { throw new InvalidCastException($"Can't convert the return value of the {this.DisplayName} method from {this.MethodInfo.ReturnType.FullName} to {typeof(TValue).FullName}."); } } /// public void Invoke(params object?[] arguments) { // invoke method try { this.MethodInfo.Invoke(this.Parent, arguments); } catch (Exception ex) { throw new Exception($"Couldn't invoke the {this.DisplayName} method", ex); } } } }