Extensions.cs 3.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using ILRuntime.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. if(attribute.HasFields)
  48. {
  49. foreach (var j in attribute.Fields)
  50. {
  51. var field = it.GetField(j.Name, out int index);
  52. if (field != null)
  53. ((ILRuntime.Runtime.Intepreter.ILTypeInstance)ins)[index] = j.Argument.Value;
  54. }
  55. }
  56. ins = ((ILRuntime.Runtime.Intepreter.ILTypeInstance)ins).CLRInstance;
  57. }
  58. else
  59. {
  60. param = new List<IType>();
  61. object[] p = null;
  62. if (attribute.HasConstructorArguments)
  63. {
  64. p = new object[attribute.ConstructorArguments.Count];
  65. for (int j = 0; j < attribute.ConstructorArguments.Count; j++)
  66. {
  67. var ca = attribute.ConstructorArguments[j];
  68. param.Add(appdomain.GetType(ca.Type, null, null));
  69. p[j] = ca.Value;
  70. }
  71. }
  72. ins = ((CLRMethod)at.GetConstructor(param)).ConstructorInfo.Invoke(p);
  73. if (attribute.HasProperties)
  74. {
  75. foreach (var j in attribute.Properties)
  76. {
  77. var prop = at.TypeForCLR.GetProperty(j.Name);
  78. prop.SetValue(ins, j.Argument.Value, null);
  79. }
  80. }
  81. if(attribute.HasFields)
  82. {
  83. foreach(var j in attribute.Fields)
  84. {
  85. var field = at.TypeForCLR.GetField(j.Name);
  86. field.SetValue(ins, j.Argument.Value);
  87. }
  88. }
  89. }
  90. return ins;
  91. }
  92. }
  93. }