SimpleReflection.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. List<string> dlls = FileTool.GetFile(path, "*.dll");
  27. foreach (var dll in dlls)
  28. {
  29. try
  30. {
  31. Assembly ass = Assembly.LoadFile(dll);
  32. if (ass.FullName == name)
  33. return ass;
  34. }
  35. catch { }
  36. }
  37. return null;
  38. }
  39. public T Do<T>(string file, string className, string methodName, object[] args, object[] values)
  40. {
  41. //获取dll中所有类
  42. Type[] types = Assembly.LoadFile(file).GetTypes();
  43. //从列表中获取指定类
  44. Type cls = types.FirstOrDefault(x => x.FullName.Contains(className));
  45. if (cls != null)
  46. {
  47. //创建实例
  48. object instance = Activator.CreateInstance(cls, args);
  49. //根据名称获取方法
  50. MethodInfo method = cls.GetMethod(methodName);
  51. //执行方法
  52. object result = method.Invoke(instance, values);
  53. return (T)result;
  54. }
  55. return default(T);
  56. }
  57. }
  58. }