1
0
Files
common/AMWD.Common/Extensions/ReflectionExtensions.cs

43 lines
1.8 KiB
C#

using System.Reflection;
using System.Threading.Tasks;
namespace AMWD.Common.Extensions
{
/// <summary>
/// Extension methods for <see cref="System.Reflection"/>.
/// </summary>
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public static class ReflectionExtensions
{
/// <summary>
/// Calls a method from it's reflection asynchronously without result.
/// </summary>
/// <param name="methodInfo">The <see cref="MethodInfo"/> to call on an object.</param>
/// <param name="obj">The reflected instance to call the method on.</param>
/// <param name="parameters">The parameters of the called method.</param>
/// <returns>An awaitable <see cref="Task"/>.</returns>
public static async Task CallAsync(this MethodInfo methodInfo, object obj, params object[] parameters)
{
var task = (Task)methodInfo.Invoke(obj, parameters);
await task.ConfigureAwait(false);
}
/// <summary>
/// Invokes a method from it's reflection asynchronously with a result.
/// </summary>
/// <typeparam name="TResult">The result type, that is expected (and casted to).</typeparam>
/// <param name="methodInfo">The <see cref="MethodInfo"/> to invoke on an object.</param>
/// <param name="obj">The reflected instance to invoke the method on.</param>
/// <param name="parameters">The parameters of the called method.</param>
/// <returns>An awaitable <see cref="Task"/> with result.</returns>
public static async Task<TResult> InvokeAsync<TResult>(this MethodInfo methodInfo, object obj, params object[] parameters)
{
var task = (Task)methodInfo.Invoke(obj, parameters);
await task.ConfigureAwait(false);
var resultPropertyInfo = task.GetType().GetProperty("Result");
return (TResult)resultPropertyInfo.GetValue(task);
}
}
}