1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- using CommonLang.Property;
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace CommonAIServer
- {
- public static class ServerUtils
- {
- public static object DynamicToObject(dynamic src, object dst)
- {
- var dtype = dst.GetType();
- if (dtype.IsPrimitive || dtype.IsAssignableFrom(typeof(string)))
- {
- return src;
- }
- foreach (var f in dtype.GetFields())
- {
- try
- {
- dynamic sfv = src[f.Name];
- if (sfv != null)
- {
- if (f.FieldType.IsPrimitive || f.FieldType.IsAssignableFrom(typeof(string)))
- {
- f.SetValue(dst, sfv);
- }
- else if (f.FieldType.IsEnum)
- {
- var dfv = Enum.Parse(f.FieldType, sfv.ToString());
- f.SetValue(dst, dfv);
- }
- else if (f.FieldType.IsArray)
- {
- ArrayList temp = new ArrayList();
- var elementType = f.FieldType.GetElementType();
- foreach (dynamic sitem in sfv)
- {
- var ditem = ReflectionUtil.CreateInstance(elementType);
- ditem = DynamicToObject(sitem, ditem);
- temp.Add(ditem);
- }
- Array dfv = ReflectionUtil.CreateInstance(f.FieldType, temp.Count) as Array;
- for (int i=0; i < temp.Count; i++)
- {
- dfv.SetValue(temp[i], i);
- }
- f.SetValue(dst, dfv);
- }
- else if (f.FieldType.GetInterface(typeof(IList).Name) != null)
- {
- var dfv = ReflectionUtil.CreateInstance(f.FieldType) as IList;
- var elementType = f.FieldType.GetGenericArguments()[0];
- foreach (dynamic sitem in sfv)
- {
- var ditem = ReflectionUtil.CreateInstance(elementType);
- ditem = DynamicToObject(sitem, ditem);
- dfv.Add(ditem);
- }
- f.SetValue(dst, dfv);
- }
- else
- {
- var dfv = ReflectionUtil.CreateInstance(f.FieldType);
- dfv = DynamicToObject(sfv, dfv);
- f.SetValue(dst, dfv);
- }
- }
- }
- catch (Exception err)
- {
- Console.WriteLine(err.Message);
- }
- }
- return dst;
- }
- }
- }
|