/// <summary> /// 返回一个实体类型的描述信息(全部属性及字段)。 /// </summary> /// <param name="type"></param> /// <returns></returns> public static ModelDescripton GetModelDescripton(Type type) { if (type == null) { throw new ArgumentNullException("type"); } string key = type.FullName; ModelDescripton mm = (ModelDescripton)s_modelTable[key]; if (mm == null) { List <DataMember> list = new List <DataMember>(); (from p in type.GetProperties(BindingFlags.Instance | BindingFlags.Public) select new PropertyMember(p)).ToList().ForEach(x => list.Add(x)); (from f in type.GetFields(BindingFlags.Instance | BindingFlags.Public) select new FieldMember(f)).ToList().ForEach(x => list.Add(x)); mm = new ModelDescripton { Fields = list.ToArray() }; s_modelTable[key] = mm; } return(mm); }
/// <summary> /// 返回一个实体类型的指定名称的数据成员 /// </summary> /// <param name="type"></param> /// <param name="name"></param> /// <returns></returns> public static DataMember GetMemberByName(Type type, string name, bool ifNotFoundThrowException) { ModelDescripton description = GetModelDescripton(type); foreach (DataMember member in description.Fields) { if (member.Name == name) { return(member); } } if (ifNotFoundThrowException) { throw new ArgumentOutOfRangeException( string.Format("指定的成员 {0} 在类型 {1} 中并不存在。", name, type.ToString())); } return(null); }
/// <summary> /// 根据HttpRequest填充一个数据实体。 /// 这里不支持嵌套类型的数据实体,且要求各数据成员都是简单的数据类型。 /// </summary> /// <param name="request"></param> /// <param name="model"></param> public static void FillModel(HttpRequest request, object model, string paramName) { ModelDescripton descripton = ReflectionHelper.GetModelDescripton(model.GetType()); object val = null; foreach (DataMember field in descripton.Fields) { if (field.Ignore) { continue; } // 这里的实现方式不支持嵌套类型的数据实体。 // 如果有这方面的需求,可以将这里改成递归的嵌套调用。 val = GetValueByNameAndTypeFrommRequest( request, field.Name, field.Type.GetRealType(), paramName); if (val != null) { field.SetValue(model, val); } } }
/// <summary> /// 返回一个实体类型的描述信息(全部属性及字段)。 /// </summary> /// <param name="type"></param> /// <returns></returns> public static ModelDescripton GetModelDescripton(Type type) { if (type == null) throw new ArgumentNullException("type"); string key = type.FullName; ModelDescripton mm = (ModelDescripton)s_modelTable[key]; if (mm == null) { List<DataMember> list = new List<DataMember>(); (from p in type.GetProperties(BindingFlags.Instance | BindingFlags.Public) select new PropertyMember(p)).ToList().ForEach(x => list.Add(x)); (from f in type.GetFields(BindingFlags.Instance | BindingFlags.Public) select new FieldMember(f)).ToList().ForEach(x => list.Add(x)); mm = new ModelDescripton { Fields = list.ToArray() }; s_modelTable[key] = mm; } return mm; }