1
0
mirror of synced 2024-12-18 04:45:55 +01:00
TaikoSoundEditor/Collections/Collection.cs

52 lines
1.7 KiB
C#
Raw Normal View History

2023-10-01 18:40:41 +02:00
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
2023-10-01 21:40:27 +02:00
using System.Linq;
2023-10-01 18:40:41 +02:00
using System.Text.Json.Serialization;
using TaikoSoundEditor.Commons.IO;
namespace TaikoSoundEditor.Collections
{
public static class Collections
{
public static Collection<T> FromJson<T>(string json, Type expectedItemType)
{
var colType = MakeGeneric(expectedItemType);
Debug.WriteLine(json);
var col = Json.Deserialize(colType, json);
var items = colType.GetProperty("Items").GetValue(col) as IEnumerable;
var result = new Collection<T>();
foreach (var item in items)
{
if (item is T tItem) result.Items.Add(tItem);
else throw new InvalidOperationException("Json parse error");
}
return result;
}
public static Type MakeGeneric(Type type) => typeof(Collection<>).MakeGenericType(type);
2023-10-01 21:40:27 +02:00
public static object Instantiate(Type type) => Activator.CreateInstance(MakeGeneric(type));
2023-10-01 18:40:41 +02:00
}
public class Collection<T>
{
[JsonPropertyName("items")]
2023-10-01 21:40:27 +02:00
public List<T> Items { get; set; } = new List<T>();
public object Cast(Type type)
{
var col = Collections.Instantiate(type);
var itemsProp = col.GetType().GetProperty("Items");
var add = itemsProp.PropertyType.GetMethod("Add");
var items = itemsProp.GetValue(col);
foreach (var item in Items)
add.Invoke(items, new object[] { Convert.ChangeType(item, type) });
return col;
}
2023-10-01 18:40:41 +02:00
}
}