SimpleReflection.cs 2.1 KB

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