ParamDictionary.cs 8.11 KB
Newer Older
潘栩锋's avatar
潘栩锋 committed
1 2
using Newtonsoft.Json.Linq;
using System;
潘栩锋's avatar
潘栩锋 committed
3
using System.CodeDom;
潘栩锋's avatar
潘栩锋 committed
4 5 6 7 8 9
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
潘栩锋's avatar
潘栩锋 committed
10
using static Misc.BindingOperations;
潘栩锋's avatar
潘栩锋 committed
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32

namespace Misc
{
    public class ParamDictionary
    {

        List<KeyValueCell> cells = new List<KeyValueCell>();

        /// <summary>
        /// 获取值
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void SetValue(string key, object value) 
        {
            var cell = cells.Find(c => c.Key == key);
            if (cell == null)
            {
                cell = new KeyValueCell() { Key = key, Value = value };//, Type = value.GetType() };
                cell.IsConverted = true;
                cells.Add(cell);
                ValueChanged?.Invoke(this, new ParamDictionaryValueChangedEventArgs() { Key = key, Value = value });
33
                Save();
潘栩锋's avatar
潘栩锋 committed
34 35 36 37 38 39 40 41
            }
            else
            {
                cell.IsConverted = true;
                if (cell.Value != value)
                {
                    cell.Value = value;
                    ValueChanged?.Invoke(this, new ParamDictionaryValueChangedEventArgs() { Key = key, Value = value });
42
                    Save();
潘栩锋's avatar
潘栩锋 committed
43 44 45 46 47 48 49 50 51 52 53 54 55 56
                }
            }
        }

        /// <summary>
        /// 获取值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T GetValue<T>(string key) 
        {
            return GetValue<T>(key, default(T));
        }
潘栩锋's avatar
潘栩锋 committed
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
        public object GetValue(Type type, string key, object defaultValue)
        {
            var cell = cells.Find(c => c.Key == key);
            if (cell == null)
            {
                cell = new KeyValueCell() { Key = key, Value = defaultValue };
                cell.IsConverted = true;
                cells.Add(cell);
                return cell.Value;
            }
            else
            {
                if (cell.IsConverted)
                    return cell.Value;
                else
                {
                    cell.ToValue(type);
                    return cell.Value;
                }
            }
        }
        public object GetValue(Type type, string key)
        {
            var cell = cells.Find(c => c.Key == key);
            if (cell == null)
            {
                return null;
            }
            else
            {
                if (cell.IsConverted)
                    return cell.Value;
                else
                {
                    cell.ToValue(type);
                    return cell.Value;
                }
            }
        }
潘栩锋's avatar
潘栩锋 committed
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120

        /// <summary>
        /// 获取值,如果没有返回默认值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public T GetValue<T>(string key, T defaultValue)
        {
            var cell = cells.Find(c => c.Key == key);
            if (cell == null)
            {
                cell = new KeyValueCell() { Key = key, Value = defaultValue };
                cell.IsConverted = true;
                cells.Add(cell);
                return (T)cell.Value;
            }
            else
            {
                if (cell.IsConverted)
                    return (T)cell.Value;
                else
                {
                    cell.ToValue<T>();
121
                    //var type = cell.Value.GetType();
潘栩锋's avatar
潘栩锋 committed
122 123 124 125 126 127

                    return (T)cell.Value;
                }
            }
        }

潘栩锋's avatar
潘栩锋 committed
128 129 130 131 132 133 134 135 136
        /// <summary>
        /// 双向绑定
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="src"></param>
        /// <param name="target"></param>
        /// <param name="propertyName"></param>
        /// <param name="defaultValue"></param>
        public void SetBinding<T>(INotifyPropertyChanged target, string propertyName, T defaultValue)
137 138 139 140 141 142 143 144 145 146 147 148 149 150
        {
            SetBinding<T>(target, propertyName, propertyName, defaultValue);
        }

        /// <summary>
        /// 双向绑定
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="src"></param>
        /// <param name="target"></param>
        /// <param name="propertyName"></param>
        /// <param name="key"></param>
        /// <param name="defaultValue"></param>
        public void SetBinding<T>(INotifyPropertyChanged target, string propertyName, string key, T defaultValue)
潘栩锋's avatar
潘栩锋 committed
151 152 153 154 155
        {
            Type type_s = target.GetType();
            System.Reflection.PropertyInfo pi_t = type_s.GetProperty(propertyName);
            if (pi_t == null)
                return;
156
            object obj = this.GetValue<T>(key, defaultValue);
潘栩锋's avatar
潘栩锋 committed
157 158 159 160 161 162 163
            pi_t.SetValue(target, obj);

            target.PropertyChanged += (s, e) =>
            {
                if (e.PropertyName == propertyName)
                {
                    object o = pi_t.GetValue(target);
164
                    this.SetValue(key, o);
潘栩锋's avatar
潘栩锋 committed
165 166
                }
            };
167

潘栩锋's avatar
潘栩锋 committed
168 169
            ValueChanged += (s, e) =>
            {
170 171 172
                if (e.Key == key)
                {
                    pi_t.SetValue(target, e.Value);
潘栩锋's avatar
潘栩锋 committed
173 174 175 176
                }
            };
        }

潘栩锋's avatar
潘栩锋 committed
177 178 179 180 181 182 183 184
        private string path;

        public event UiParamDictionaryValueChangedHandler ValueChanged;
        public ParamDictionary(string path = "paramDict.json")
        {
            this.path = path;
            Load();
        }
185
        void Load()
潘栩锋's avatar
潘栩锋 committed
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
        {
            if (!File.Exists(path))
                return;
            try
            {
                string json = File.ReadAllText(path);
                var cells = Newtonsoft.Json.JsonConvert.DeserializeObject<List<KeyValueCell>>(json);
                this.cells = cells;
            }
            catch (Exception e)
            {
                //logger.Error(e, "Load 出错");
            }
        }
        public void Save()
        {
潘栩锋's avatar
潘栩锋 committed
202 203
            
            foreach (var cell in cells)
潘栩锋's avatar
潘栩锋 committed
204
            {
潘栩锋's avatar
潘栩锋 committed
205 206
                try
                {
潘栩锋's avatar
潘栩锋 committed
207
                    cell.ToToken();
潘栩锋's avatar
潘栩锋 committed
208 209 210 211 212 213 214 215
                }
                catch (Exception e)
                { 
                    
                }
            }
            try
            {
潘栩锋's avatar
潘栩锋 committed
216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
                string json = Newtonsoft.Json.JsonConvert.SerializeObject(cells, Newtonsoft.Json.Formatting.Indented);
                File.WriteAllText(path, json);
            }
            catch (Exception e)
            {
                //logger.Error(e, "Save 出错");
            }
        }
    }
    public delegate void UiParamDictionaryValueChangedHandler(object sender, ParamDictionaryValueChangedEventArgs e);

    public class ParamDictionaryValueChangedEventArgs : EventArgs
    {
        public string Key;
        public object Value;
    }
    
    
    public class KeyValueCell : INotifyPropertyChanged
    {
        public string Key { get; set; }

        [Newtonsoft.Json.JsonIgnore]
        public object Value { get; set; }

        /// <summary>
        /// 已经转换为object 非 JObject 与 JArray
        /// </summary>
        [Newtonsoft.Json.JsonIgnore]
        public bool IsConverted { get; set; }

        [Newtonsoft.Json.JsonProperty("Value")]
        public JToken Token { get; set; }

        public event PropertyChangedEventHandler PropertyChanged;

        public override string ToString()
        {
            return $"[{Key}]={Newtonsoft.Json.JsonConvert.SerializeObject(Value)}";
        }

        /// <summary>
        /// Value转为类型T
        /// </summary>
        /// <typeparam name="T"></typeparam>
        public void ToValue<T>() 
        {
            IsConverted = true;
            if (Token == null)
                return;
            Value = Token.ToObject<T>();
        }
潘栩锋's avatar
潘栩锋 committed
268 269 270 271 272 273 274
        public void ToValue(Type type)
        {
            IsConverted = true;
            if (Token == null)
                return;
            Value = Token.ToObject(type);
        }
潘栩锋's avatar
潘栩锋 committed
275 276 277 278 279 280
        public void ToToken() 
        {
            Token = JToken.FromObject(Value);
        }
    }
}