C#
/// <summary> /// Model to Model /// </summary> /// <typeparam name="T">类</typeparam> /// <typeparam name="Tn">新的类</typeparam> /// <param name="objmodel">T类的参数值</param> /// <param name="nobjModel">Tn类一个空的实例化</param> /// <returns></returns> public static Tn ModelToModel<T, Tn>(T objmodel, Tn nobjModel) { Tn Nobjmodel = nobjModel; //被继承的类 Type modelType = typeof(T); Type newModel = typeof(Tn);//继承后的新类 PropertyInfo[] newpropertys = modelType.GetProperties();//列举出新的类中信息 //循环新类的属性 foreach (PropertyInfo pi in newpropertys) { string ParaName = pi.Name;//参数名称 string ParamType = pi.PropertyType.Name;//字段类型 int/DateTime/string 等等 object vaule = modelType.GetProperty(ParaName).GetValue(objmodel, null);//从被继承的类中根据相同字段名称读取类的值 if (vaule != null) { var property = newModel.GetProperty(ParaName); if(property!=null) property.SetValue(Nobjmodel, vaule, null);//给新版本的类参数赋值 } } return Nobjmodel; }
欢迎转载,转载请注明出处:http://www.cnblogs.com/Tonyyang/