You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
3.5 KiB

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace Shentun.Utilities
{
public class ReflectionHelper
{
public static async Task<T> InvokeAsync<T>(string assemblyName, string className, string classConstructorArg, string methodName, object[] args = null)
{
Assembly assembly = Assembly.Load(assemblyName);
Type type = assembly.GetType(className);
// 创建类的实例
object instance = Activator.CreateInstance(type, classConstructorArg);
// 获取方法信息
MethodInfo method = type.GetMethod(methodName);
// 调用方法,如果方法需要参数,可以传入对应的参数数组,例如: new object[] { arg1, arg2 }
T returnValue;
var isAsync = (method.ReturnType == typeof(Task) ||
(method.ReturnType.IsGenericType && method.ReturnType.GetGenericTypeDefinition() == typeof(Task<>)));
if (isAsync)
{
// 使用反射调用方法
//object returnValue = method.Invoke(instance, args);
returnValue = await (Task<T>)method.Invoke(instance, args);
}
else
{
returnValue = (T)method.Invoke(instance, args);
}
return returnValue;
}
public static async Task InvokeAsync(string assemblyName, string className, string classConstructorArg, string methodName, object[] args = null)
{
Assembly assembly = Assembly.Load(assemblyName);
Type type = assembly.GetType(className);
// 创建类的实例
object instance = Activator.CreateInstance(type, classConstructorArg);
// 获取方法信息
MethodInfo method = type.GetMethod(methodName);
// 调用方法,如果方法需要参数,可以传入对应的参数数组,例如: new object[] { arg1, arg2 }
var isAsync = (method.ReturnType == typeof(Task) ||
(method.ReturnType.IsGenericType && method.ReturnType.GetGenericTypeDefinition() == typeof(Task<>)));
if (isAsync)
{
// 使用反射调用方法
//object returnValue = method.Invoke(instance, args);
await (Task)method.Invoke(instance, args);
}
else
{
method.Invoke(instance, args);
}
return ;
}
public static void Invoke(string assemblyName, string className, string classConstructorArg, string methodName, object[] args = null)
{
Assembly assembly = Assembly.Load(assemblyName);
Type type = assembly.GetType(className);
// 创建类的实例
object instance = Activator.CreateInstance(type, classConstructorArg);
// 获取方法信息
MethodInfo method = type.GetMethod(methodName);
// 调用方法,如果方法需要参数,可以传入对应的参数数组,例如: new object[] { arg1, arg2 }
//var isAsync = (method.ReturnType == typeof(Task) ||
// (method.ReturnType.IsGenericType && method.ReturnType.GetGenericTypeDefinition() == typeof(Task<>)));
//if (isAsync)
//{
// throw new Exception("该方法不支持异步");
//}
method.Invoke(instance, args);
return;
}
}
}