一个自动生成模型的辅助类,可以从Request.Form或者Request.QueryString中自动生成Model
public class Person<T> { public string name; public bool sex; public int age; public DateTime birthday; public DateTime? now; public T desc; } //main方法下面的 var NVC = new NameValueCollection(); NVC.Add("name", "白菜"); NVC.Add("sex", "1"); NVC.Add("age", "23"); NVC.Add("birthday", "1989-06-27"); NVC.Add("now", "2011-12-08"); NVC.Add("Desc", ".net程序员"); var person = NVC.ModelGeneration<Person<string>>();
以下为扩展方法
public static class ModelGenerationExtension { /// <summary> /// 从名值对参数中自动填充模型 /// </summary> public static T ModelGeneration<T>(this NameValueCollection nvc) { var type = typeof(T); var obj = (T)Activator.CreateInstance(type); var bindflag = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.GetField; var fileds = type.GetFields(bindflag); foreach (var filed in fileds) { var val = nvc[filed.Name]; var fType = filed.FieldType; if (fType.IsGenericType && fType.GetGenericTypeDefinition() == typeof(Nullable<>)) { //泛型参数 可空类型 fType = fType.GetGenericArguments()[0]; } try { if (typeof(bool) == fType && val.ToLower() != "true" && val.ToLower() != "false") if (val == "1") val = "true"; else val = "false"; type.GetField(filed.Name, bindflag).SetValue(obj, Convert.ChangeType(val, fType)); } catch { type.GetField(filed.Name, bindflag).SetValue(obj, Activator.CreateInstance(fType)); } } return obj; } }
当然可以像这样应用:
var model= Request.Form.ModelGeneration<你的类型>();