C# 实体类转换的两种方式
以下提供两种方式,一种是序列化,一种是泛型+反射;
实现功能:
两个实体类数据转换赋值
开发环境:
开发工具: Visual Studio 2013
.NET Framework版本:4.5
实现代码:
//学生类
private class Student
{
public string name { get; set; }
public int age { get; set; }
public string className { get; set; }
}
//教师类
private class Teacher
{
public string name { get; set; }
public int age { get; set; }
public string sex { get; set; }
}
//给学生类赋值
Student student = new Student
{
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;
string json = JsonConvert.SerializeObject(student);
teacher = JsonConvert.DeserializeObject<Teacher>(json);
Console.WriteLine(teacher.name);//张三
Console.WriteLine(teacher.age); //20
Console.WriteLine(teacher.sex);
//泛型+反射
public 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());
if (name != null && pi.PropertyType.Name == name.PropertyType.Name)
{
pi.SetValue(ret, name.GetValue(pModel, null), null);
}
}
}
return ret;
}
————————————————
实现功能:
两个实体类数据转换赋值
开发环境:
开发工具: Visual Studio 2013
.NET Framework版本:4.5
实现代码:
//学生类
private class Student
{
public string name { get; set; }
public int age { get; set; }
public string className { get; set; }
}
//教师类
private class Teacher
{
public string name { get; set; }
public int age { get; set; }
public string sex { get; set; }
}
//给学生类赋值
Student student = new Student
{
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;
string json = JsonConvert.SerializeObject(student);
teacher = JsonConvert.DeserializeObject<Teacher>(json);
Console.WriteLine(teacher.name);//张三
Console.WriteLine(teacher.age); //20
Console.WriteLine(teacher.sex);
//泛型+反射
public 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());
if (name != null && pi.PropertyType.Name == name.PropertyType.Name)
{
pi.SetValue(ret, name.GetValue(pModel, null), null);
}
}
}
return ret;
}
————————————————