78 lines
2.2 KiB
C#
78 lines
2.2 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="bindingAttr"></param>
|
|
/// <param name="args"></param>
|
|
public static void InvokeGenericMethod(
|
|
this Type source,
|
|
string methodName,
|
|
Type runtimeType,
|
|
BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic,
|
|
params object[] args
|
|
)
|
|
{
|
|
//
|
|
var overLoads = source.GetGenericMethodInfo(
|
|
methodName: methodName,
|
|
bindingAttr: bindingAttr
|
|
);
|
|
if (!overLoads.HasChild())
|
|
{
|
|
return;
|
|
}
|
|
|
|
//
|
|
var method = overLoads.ElementAt(0);
|
|
MethodInfo genericMethod = method.MakeGenericMethod(runtimeType);
|
|
|
|
//
|
|
var gParams = new object[]
|
|
{
|
|
source
|
|
}
|
|
.Concat(args)
|
|
.ToArray();
|
|
|
|
//
|
|
genericMethod.Invoke(null, gParams);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Extract a Generic Method's Overloads ...
|
|
/// </summary>
|
|
/// <param name="source"></param>
|
|
/// <param name="methodName"></param>
|
|
/// <param name="bindingAttr"></param>
|
|
/// <returns></returns>
|
|
public static List<MethodInfo> GetGenericMethodInfo(
|
|
this Type source,
|
|
string methodName,
|
|
BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.Static | BindingFlags.NonPublic
|
|
)
|
|
{
|
|
//
|
|
var result = source
|
|
.GetMethods(bindingAttr)
|
|
.Where(mi =>
|
|
mi.Name == methodName &&
|
|
mi.IsGenericMethodDefinition)
|
|
.ToList();
|
|
|
|
//
|
|
return result;
|
|
}
|
|
}
|
|
} |