如何以递归方式将字典转换为类和子类?这些是我的课程:
public class UiItem
{
public string id { get; set; }
public string text { get; set; }
public Rect rect { get; set; }
}
public class Rect
{
public int height { get; set; }
public int width { get; set; }
public int y { get; set; }
public int x { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我写了这个,但我不知道如何Rect在类中创建对象UiItem:
public static T GetObject<T>(this Dictionary<string, object> dict)
{
Type type = typeof(T);
var obj = Activator.CreateInstance(type);
foreach (var kv in dict)
{
var prop = type.GetProperty(kv.Key);
object value = kv.Value;
if (kv.Value.GetType() == typeof(Dictionary<string, object>))
{
value = GetObject<_???_>((Dictionary<string, object>) value) // <= This line
}
if(prop == null) continue;
prop.SetValue(obj, value, null);
}
return (T)obj;
}
Run Code Online (Sandbox Code Playgroud)
最简单的方法是将类型作为参数传递,而不是使用泛型方法。那么这就是:
public static Object GetObject(this Dictionary<string, object> dict, Type type)
{
var obj = Activator.CreateInstance(type);
foreach (var kv in dict)
{
var prop = type.GetProperty(kv.Key);
if(prop == null) continue;
object value = kv.Value;
if (value is Dictionary<string, object>)
{
value = GetObject((Dictionary<string, object>) value, prop.PropertyType); // <= This line
}
prop.SetValue(obj, value, null);
}
return obj;
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以创建一个执行转换的通用版本:
public static T GetObject<T>(this Dictionary<string, object> dict)
{
return (T)GetObject(dict, typeof(T));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15006 次 |
| 最近记录: |