CsvCompatible.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. using System;
  2. using System.Globalization;
  3. using System.Linq;
  4. using System.Reflection;
  5. using System.Text;
  6. using UnityEngine;
  7. namespace SchoenLogger
  8. {
  9. public class CsvCompatible
  10. {
  11. const BindingFlags Bindings = BindingFlags.Public |
  12. BindingFlags.NonPublic |
  13. BindingFlags.Instance;
  14. public virtual string ToCsv()
  15. {
  16. StringBuilder csvString = new StringBuilder();
  17. FieldInfo[] fields = this.GetType()
  18. .GetFields(Bindings)
  19. .ToArray();
  20. foreach (FieldInfo fieldInfo in fields)
  21. {
  22. if (Attribute.IsDefined(fieldInfo, typeof(SerializeField)))
  23. {
  24. if (fieldInfo.FieldType == typeof(float))
  25. {
  26. csvString.Append(";" + ((float)fieldInfo.GetValue(this)).ToString("G", CultureInfo.InvariantCulture));
  27. continue;
  28. }
  29. if (fieldInfo.FieldType == typeof(double))
  30. {
  31. csvString.Append(";" + ((double)fieldInfo.GetValue(this)).ToString("G", CultureInfo.InvariantCulture));
  32. continue;
  33. }
  34. csvString.Append(";" + fieldInfo.GetValue(this).ToString());
  35. }
  36. }
  37. return csvString.ToString();
  38. }
  39. public static string GetCsvHeader<T>()
  40. {
  41. StringBuilder headerString = new StringBuilder();
  42. FieldInfo[] fields = typeof(T)
  43. .GetFields(Bindings)
  44. .ToArray();
  45. foreach (FieldInfo fieldInfo in fields)
  46. {
  47. if (Attribute.IsDefined(fieldInfo, typeof(SerializeField)))
  48. headerString.Append(";" + fieldInfo.Name);
  49. }
  50. return headerString.ToString();
  51. }
  52. }
  53. }