- 控制台 退出
登录 注册
返回列表 >> C#实体类转换的两种方式小结
将一个实体类的数据赋值到另一个实体类中(亦或者实现深拷贝)。
//学生类
private
class
Student
{
public
string
name {
get
;
set
; }
int
age {
className {
}
//教师类
Teacher
sex {
//给学生类赋值
Student student =
new
name =
张三
,
age = 20,
className =
六
};
//泛型+反射方式
Teacher teacher = ConvertModel<Teacher, Student>(student);
Console.WriteLine(teacher.name);
//张三
Console.WriteLine(teacher.age);
//20
Console.WriteLine(teacher.sex);
//JSON序列化方式
teacher =
null
json = JsonConvert.SerializeObject(student);
teacher = JsonConvert.DeserializeObject<Teacher>(json);
//泛型+反射
static
T ConvertModel<T, P>(P pModel)
T ret = System.Activator.CreateInstance<T>();
List<PropertyInfo> p_pis = pModel.GetType().GetProperties().ToList();
PropertyInfo[] t_pis =
typeof
(T).GetProperties();
foreach
(PropertyInfo pi
in
t_pis)
//可写入数据
if
(pi.CanWrite)
//忽略大小写
var name = p_pis.Find(s => s.Name.ToLower() == pi.Name.ToLower());
(name !=
pi.PropertyType.Name == name.PropertyType.Name)
pi.SetValue(ret, name.GetValue(pModel,
),
);
return
ret;
jsonstr = JsonConvert.SerializeObject(model);
以上为个人经验,希望能给大家一个参考,也希望大家多多支持陆零网络。
TOP