/// <summary> /// 根据指定的属性串得到函数体 /// </summary> /// <param name="type">类型</param> /// <param name="obj">对象</param> private static string MakeFunction(Type type, object obj) { object tmp; Type tp; PropertyInfo[] pi = type.GetProperties(); StringBuilder fun = new StringBuilder(); fun.AppendLine("function(){"); foreach (PropertyInfo p in pi) { if (!p.CanRead) { continue; } tmp = p.GetValue(obj, null); fun.AppendFormat(" this.{0} = ", p.Name); //对bool值的处理 if (tmp == null) { fun.Append("null"); fun.AppendLine(";"); continue; } tp = tmp.GetType(); if (tp == typeof(Boolean)) { fun.Append(tmp.ToString().ToLower()); fun.AppendLine(";"); continue; } if (tp.IsArray)//数组 { fun.Append(MakeArray((object[])tmp)); continue; } if (tp.GetCustomAttributes(typeof(AjaxObject), true).Length > 0) //对象 { fun.Append("new "); fun.Append(MakeFunction(tp, tmp)); continue; } //以外所有输出 fun.AppendFormat("unescape('{0}')", AjaxUtils.AjaxEncode(tmp.ToString())); fun.AppendLine(";"); } fun.AppendLine("}"); return(fun.ToString()); }
/// <summary> /// 根据指定的对象数组返回一个数组体 /// </summary> /// <param name="arr">数组</param> private static string MakeArray(object[] arr) { StringBuilder fun = new StringBuilder(); object tmp; Type type; fun.AppendLine("new Array("); for (int i = 0; i < arr.Length; i++) { tmp = arr[i]; type = tmp.GetType(); if (tmp == null) { fun.AppendLine("null"); } else if (type.IsArray) { fun.Append(MakeArray((object[])tmp)); } else if (type.GetCustomAttributes(typeof(AjaxObject), true).Length > 0) //对象 { fun.Append("new "); //新涵数体 fun.Append(MakeFunction(type, tmp)); } else { fun.AppendFormat("unescape('{0}')", AjaxUtils.AjaxEncode(tmp.ToString())); } if (i == arr.Length - 1) //当等于时不须要再加,防止因最后一个增加所导致的错误 { fun.AppendLine(); } else { fun.AppendLine(","); } } //加上最后一个 fun.AppendLine(" )"); return(fun.ToString()); }