45 lines
1.4 KiB
C#
45 lines
1.4 KiB
C#
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using System.Dynamic;
|
|
|
|
namespace Framework.Shared.Abstraction {
|
|
public abstract class Packet {
|
|
|
|
public abstract void LoadData(ExpandoObject data);
|
|
|
|
protected T Convert<T>(ExpandoObject prop, string variable) {
|
|
var dict = (IDictionary<string, object>)prop;
|
|
return (T)Convert(dict[variable], typeof(T));
|
|
}
|
|
|
|
protected List<T> ConvertList<T>(ExpandoObject prop, string variable) {
|
|
var dict = (IDictionary<string, object>)prop;
|
|
return (List<T>)Convert(dict[variable], typeof(T));
|
|
}
|
|
|
|
protected T[] ConvertArray<T>(ExpandoObject prop, string variable) {
|
|
return ConvertList<T>(prop, variable).ToArray();
|
|
}
|
|
|
|
private object Convert(object prop, Type generic) {
|
|
var type = prop.GetType();
|
|
|
|
if (type == typeof(List<object>)) {
|
|
var rawList = prop as IList ?? new List<object>();
|
|
|
|
var listType = typeof(List<>).MakeGenericType(generic);
|
|
var list = Activator.CreateInstance(listType) as IList ?? new List<object>();
|
|
|
|
foreach (var element in rawList) {
|
|
list.Add(Convert(element, generic));
|
|
}
|
|
|
|
return list;
|
|
}
|
|
|
|
return System.Convert.ChangeType(prop, generic);
|
|
}
|
|
|
|
}
|
|
} |