SerializableArray.cs 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System;
  2. using System.Runtime.CompilerServices;
  3. namespace BansheeEngine
  4. {
  5. #pragma warning disable 649
  6. /// <summary>
  7. /// Allows you to access meta-data about a managed array and its children. Similar to Reflection but simpler and faster.
  8. /// </summary>
  9. public sealed class SerializableArray : ScriptObject
  10. {
  11. private SerializableProperty.FieldType elementType;
  12. private Type internalElementType;
  13. private SerializableProperty parentProperty;
  14. /// <summary>
  15. /// Type of elements stored in the array.
  16. /// </summary>
  17. public SerializableProperty.FieldType ElementType
  18. {
  19. get { return elementType; }
  20. }
  21. /// <summary>
  22. /// Constructor for use by the runtime only.
  23. /// </summary>
  24. /// <param name="internalElementType">C# type of the elements in the array.</param>
  25. /// <param name="parentProperty">Property this array belongs to.</param>
  26. private SerializableArray(Type internalElementType, SerializableProperty parentProperty)
  27. {
  28. this.parentProperty = parentProperty;
  29. this.internalElementType = internalElementType;
  30. elementType = SerializableProperty.DetermineFieldType(internalElementType);
  31. }
  32. /// <summary>
  33. /// Returns a serializable property for a specific array element.
  34. /// </summary>
  35. /// <param name="elementIdx">Index of the element in the array.</param>
  36. /// <returns>Serializable property for the element that may be used for querying element meta-data.</returns>
  37. public SerializableProperty GetProperty(int elementIdx)
  38. {
  39. SerializableProperty.Getter getter = () =>
  40. {
  41. Array array = parentProperty.GetValue<Array>();
  42. if (array != null)
  43. return array.GetValue(elementIdx);
  44. else
  45. return null;
  46. };
  47. SerializableProperty.Setter setter = (object value) =>
  48. {
  49. Array array = parentProperty.GetValue<Array>();
  50. if(array != null)
  51. array.SetValue(value, elementIdx);
  52. };
  53. SerializableProperty property = Internal_CreateProperty(mCachedPtr);
  54. property.Construct(ElementType, internalElementType, getter, setter);
  55. return property;
  56. }
  57. /// <summary>
  58. /// Returns number of elements in the array.
  59. /// </summary>
  60. /// <returns>Number of elements in the array.</returns>
  61. public int GetLength()
  62. {
  63. Array array = parentProperty.GetValue<Array>();
  64. if (array != null)
  65. return array.GetLength(0); // TODO - Support multi-rank arrays
  66. else
  67. return 0;
  68. }
  69. [MethodImpl(MethodImplOptions.InternalCall)]
  70. private static extern SerializableProperty Internal_CreateProperty(IntPtr nativeInstance);
  71. }
  72. }