From 9549d1302e4ed2e4165d9a39852d244b0f5b7603 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Holger=20B=C3=B6rchers?= Date: Mon, 30 Mar 2020 21:29:49 +0200 Subject: [PATCH] moved converter code to extension class --- PropertyInfoExtension.cs | 44 ++++++++++++++++++++++++++++++++++++++++ WindowViewModel.cs | 42 ++------------------------------------ 2 files changed, 46 insertions(+), 40 deletions(-) create mode 100644 PropertyInfoExtension.cs diff --git a/PropertyInfoExtension.cs b/PropertyInfoExtension.cs new file mode 100644 index 0000000..a2aa669 --- /dev/null +++ b/PropertyInfoExtension.cs @@ -0,0 +1,44 @@ +using System; +using System.Reflection; +using System.Text.Json; + +namespace ModernWpfPlayground +{ + public static class PropertyInfoExtension + { + public static PropertyInfo? Find(this PropertyInfo[] infos, string key) => Array.Find(infos, x => x.Name == key); + + public static object? Convert(this PropertyInfo? propertyInfo, JsonElement value) + { + if (propertyInfo == default) return default; + + + if (propertyInfo.PropertyType == typeof(double)) + { + return value.GetDouble(); + } + + if (propertyInfo.PropertyType == typeof(bool)) + { + return value.GetBoolean(); + } + + if (propertyInfo.PropertyType == typeof(int)) + { + return value.GetInt32(); + } + + if (propertyInfo.PropertyType.IsEnum) + { + return Enum.ToObject(propertyInfo.PropertyType, value.GetInt32()); + } + + if (propertyInfo.PropertyType == typeof(string)) + { + return value.GetString(); + } + + return default; + } + } +} \ No newline at end of file diff --git a/WindowViewModel.cs b/WindowViewModel.cs index 3f71068..bb60dc0 100644 --- a/WindowViewModel.cs +++ b/WindowViewModel.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text.Json; @@ -108,43 +107,6 @@ namespace ModernWpfPlayground public ICommand ResetViewModelCommand { get; } - private object? CastToType(string key, JsonElement value) - { - - var property = Array.Find(_properties, x => x.Name == key); - if (property == null) - { - return default; - } - - if (property.PropertyType == typeof(double)) - { - return value.GetDouble(); - } - - if (property.PropertyType == typeof(bool)) - { - return value.GetBoolean(); - } - - if (property.PropertyType == typeof(int)) - { - return value.GetInt32(); - } - - if (property.PropertyType.IsEnum) - { - return Enum.ToObject(property.PropertyType, value.GetInt32()); - } - - if (property.PropertyType == typeof(string)) - { - return value.GetString(); - } - - return default; - } - private void SaveViewModel() { var contents = JsonSerializer.Serialize(Values); @@ -169,7 +131,7 @@ namespace ModernWpfPlayground var obj = JsonSerializer.Deserialize>(contents); foreach (var (key, value) in obj) { - yield return (key, CastToType(key, value)); + yield return (key, _properties.Find(key).Convert(value)); } } }