Extensions.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Mono.Cecil;
  6. using ILRuntime.CLR.Method;
  7. using ILRuntime.CLR.TypeSystem;
  8. namespace ILRuntime.Reflection
  9. {
  10. static class Extensions
  11. {
  12. public static object CreateInstance(this CustomAttribute attribute, IType at, Runtime.Enviorment.AppDomain appdomain)
  13. {
  14. object ins;
  15. List<IType> param = null;
  16. if (at is ILType)
  17. {
  18. var it = (ILType)at;
  19. if (!attribute.HasConstructorArguments)
  20. ins = it.Instantiate(true);
  21. else
  22. {
  23. ins = it.Instantiate(false);
  24. if (param == null)
  25. param = new List<IType>();
  26. param.Clear();
  27. object[] p = new object[attribute.ConstructorArguments.Count];
  28. for (int j = 0; j < attribute.ConstructorArguments.Count; j++)
  29. {
  30. var ca = attribute.ConstructorArguments[j];
  31. param.Add(appdomain.GetType(ca.Type, null, null));
  32. p[j] = ca.Value;
  33. }
  34. var ctor = it.GetConstructor(param);
  35. appdomain.Invoke(ctor, ins, p);
  36. }
  37. if (attribute.HasProperties)
  38. {
  39. object[] p = new object[1];
  40. foreach (var j in attribute.Properties)
  41. {
  42. p[0] = j.Argument.Value;
  43. var setter = it.GetMethod("set_" + j.Name, 1);
  44. appdomain.Invoke(setter, ins, p);
  45. }
  46. }
  47. }
  48. else
  49. {
  50. param = new List<IType>();
  51. object[] p = null;
  52. if (attribute.HasConstructorArguments)
  53. {
  54. p = new object[attribute.ConstructorArguments.Count];
  55. for (int j = 0; j < attribute.ConstructorArguments.Count; j++)
  56. {
  57. var ca = attribute.ConstructorArguments[j];
  58. param.Add(appdomain.GetType(ca.Type, null, null));
  59. p[j] = ca.Value;
  60. }
  61. }
  62. ins = ((CLRMethod)at.GetConstructor(param)).ConstructorInfo.Invoke(p);
  63. if (attribute.HasProperties)
  64. {
  65. foreach (var j in attribute.Properties)
  66. {
  67. var prop = at.TypeForCLR.GetProperty(j.Name);
  68. prop.SetValue(ins, j.Argument.Value, null);
  69. }
  70. }
  71. }
  72. return ins;
  73. }
  74. }
  75. }