SimpleReflection.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using Y.Utils.FileUtils;
  8. using Y.Utils.LogUtils;
  9. namespace Y.Utils.ReflectionUtils
  10. {
  11. public class SimpleReflection : MarshalByRefObject
  12. {
  13. //public string AssemblyPath { get; set; }
  14. //public SimpleReflection(string assemblyPath)
  15. //{
  16. // AssemblyPath = assemblyPath;
  17. //}
  18. //public Assembly AssemblyResolve(object sender, ResolveEventArgs args)
  19. //{
  20. // return SearchAssembly(AssemblyPath, args.Name);
  21. //}
  22. private Assembly SearchAssembly(string path, string name)
  23. {
  24. try
  25. {
  26. List<string> dlls = FileTool.GetFile(path, "*.dll");
  27. foreach (var dll in dlls)
  28. {
  29. Assembly ass = Assembly.LoadFile(dll);
  30. if (ass.FullName == name)
  31. return ass;
  32. }
  33. }
  34. catch (Exception e)
  35. {
  36. Log.e(e.Message);
  37. }
  38. return null;
  39. }
  40. public T Do<T>(string file, string className, string methodName, object[] args, object[] values)
  41. {
  42. //获取dll中所有类
  43. Type[] types = Assembly.LoadFile(file).GetTypes();
  44. //从列表中获取指定类
  45. Type cls = types.FirstOrDefault(x => x.FullName.Contains(className));
  46. if (cls != null)
  47. {
  48. //创建实例
  49. object instance = Activator.CreateInstance(cls, args);
  50. //根据名称获取方法
  51. MethodInfo method = cls.GetMethod(methodName);
  52. //执行方法
  53. object result = method.Invoke(instance, values);
  54. return (T)result;
  55. }
  56. return default(T);
  57. }
  58. }
  59. }