moved converter code to extension class

This commit is contained in:
Holger Börchers 2020-03-30 21:29:49 +02:00
parent 97ed0d9be0
commit 9549d1302e
2 changed files with 46 additions and 40 deletions

44
PropertyInfoExtension.cs Normal file
View File

@ -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;
}
}
}

View File

@ -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<Dictionary<string, JsonElement>>(contents);
foreach (var (key, value) in obj)
{
yield return (key, CastToType(key, value));
yield return (key, _properties.Find(key).Convert(value));
}
}
}