Files
xCommons/Helpers/XGenericHelper.cs
T
2026-05-09 22:20:59 +03:30

101 lines
2.8 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using xCommons.Extensions;
namespace xCommons.Helpers
{
public static class XGenericHelper
{
/// <summary>
/// Invoke a Generic Method of Specified Type ...
/// </summary>
/// <param name="source"></param>
/// <param name="methodName"></param>
/// <param name="runtimeType"></param>
/// <param name="args"></param>
public static void InvokeGenericMethod(
this Type source,
string methodName,
Type runtimeType,
params object[] args
)
{
//
var overLoads = source.GetGenericMethodInfo(
methodName: methodName
);
if (!overLoads.HasChild())
{
return;
}
//
var method = overLoads.ElementAt(0);
MethodInfo genericMethod = method.MakeGenericMethod(runtimeType);
//
genericMethod.Invoke(null, args);
}
/// <summary>
/// Invoke a Generic Method of Specified Type ...
/// </summary>
/// <param name="source"></param>
/// <param name="methodName"></param>
/// <param name="runtimeTypes"></param>
/// <param name="args"></param>
public static void InvokeGenericMethod(
this Type source,
string methodName,
Type[] runtimeTypes,
params object[] args
)
{
//
var overLoads = source.GetGenericMethodInfo(
methodName: methodName
);
if (!overLoads.HasChild())
{
return;
}
//
// Detect a Method by Generic Types ...
// var method = overLoads.ElementAt(0);
var method = overLoads.First(m => m.GetGenericArguments().Length == runtimeTypes.Length);
MethodInfo genericMethod = method.MakeGenericMethod(runtimeTypes);
//
genericMethod.Invoke(null, args);
}
/// <summary>
/// Extract a Generic Method's Overloads ...
/// </summary>
/// <param name="source"></param>
/// <param name="methodName"></param>
/// <returns></returns>
public static List<MethodInfo> GetGenericMethodInfo(
this Type source,
string methodName
)
{
//
var methods = source
.GetMethods();
//
var result = methods
.Where(mi =>
mi.Name == methodName &&
mi.IsGenericMethodDefinition)
.ToList();
//
return result;
}
}
}