1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Reflection;
- using Microsoft.Extensions.DependencyInjection;
- namespace Bowin.Common.Utility
- {
- public static class ReflectionHelper
- {
- private static Assembly ServiceAssembly { get; set; }
- private static Assembly IServiceAssembly { get; set; }
- public static void AddServiceAssembly(this IServiceCollection service, Assembly serviceAssembly, Assembly interfaceAssembly)
- {
- ServiceAssembly = serviceAssembly;
- IServiceAssembly = interfaceAssembly;
- }
- public static object CreateByFullName(string classFullName)
- {
- try
- {
- string[] classNames = classFullName.Split(',');
- return Assembly.Load(classNames[1]).CreateInstance(classNames[0]);
- }
- catch
- {
- return null;
- }
- }
- public static object RunMethod(string methodFullName, params object[] methodParameters)
- {
- IList<string> names = methodFullName.Split('.').ToList();
- if (names.Count <= 2)
- {
- throw (new Exception("方法名输入错误。"));
- }
- string methodName = names.Last();
- names.RemoveAt(names.Count - 1);
- string className = string.Join(".", names);
- string classShortName = names.Last();
- var classType = ServiceAssembly.GetType(className);
- if (classType == null)
- {
- classType = IServiceAssembly.GetType(className);
- }
- Type myInterface;
- if (classType.IsInterface)
- {
- myInterface = classType;
- }
- else
- {
- myInterface = classType.GetInterfaces().Where(x => x.Name == "I" + classShortName).FirstOrDefault();
- }
- var myClass = HttpHelper.GetService(myInterface);
- var myMethod = myClass.GetType().GetMethod(methodName);
- try
- {
- return myMethod.Invoke(myClass, methodParameters);
- }
- catch (Exception ex)
- {
- throw (new Exception(ex.InnerException.Message));
- }
- }
- }
- }
|