summaryrefslogtreecommitdiff
path: root/WorldlineKeepers/Assets/Scripts/Data/CSVReader.cs
blob: 312eba810b5b2940a18979059315b3422ab0ec66 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
using JetBrains.Annotations;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net.Mime;
using System.Reflection;
using UnityEngine;
using yutokun;
using static UnityEngine.Rendering.DebugUI;

namespace WK.Data
{

    public class CSVReader
    {
        private static Dictionary<string/*key*/, int/*index*/> m_KeyMapping = new Dictionary<string, int>();
        private static List<List<string>> m_Rows = new List<List<string>>();

        public static List<T> Read<T>(string content) where T : new() 
        {
            m_KeyMapping.Clear();
            m_Rows.Clear();

            m_Rows = CSVParser.LoadFromString(content);
            // µÚÒ»ÐÐÊÇkey
            List<string> keys = m_Rows[0];
            for (int i = 0; i < keys.Count; ++i)
            {
                m_KeyMapping.Add(keys[i], i);
            }
            List<T> result = new List<T>();
            Type type = typeof(T);
            for (int i = 1; i < m_Rows.Count; ++i)
            {
                if (m_Rows[i][0][0] == '#') // ×¢ÊÍ
                    continue;
                List<string> row = m_Rows[i];
                T obj = new T();
                foreach(var key in m_KeyMapping)
                {
                    int index = key.Value;
                    var fieldInfo = type.GetField(key.Key);
                    if(fieldInfo != null)
                    {
                        fieldInfo.SetValue(obj, Convert.ChangeType(row[index], fieldInfo.FieldType));
                    }
                }
                result.Add(obj);
            }
            return result;
        }

    }

}