C#对象映射
1.之前在使用AutoMapper 框架感觉用着比较不够灵活,而且主要通过表达式实现对象映射 ,写着比较讨厌,当出现复杂类型和嵌套类型时性能直线下降,甚至不如序列化快。
2.针对AutoMapper 处理复杂类型和嵌套类型时性能非常不错,对于简化复制映射有点麻烦,自己实现一个简化版对对象映射方案
废话莫得讲,直接上干货
public class Article
{
public int Id { get; set; }
public string CategoryId { get; set; }
public string Title { get; set; }
public string Pic { get; set; }
public string Host { get; set; }
public string PicHost => Pic.FormatHostUrl(Host);
public string Content { get; set; }
public bool TopStatus { get; set; }
public DateTime PublishDate { get; set; }
public string LastUpdateUser { get; set; }
public DateTime LastUpdateDate { get; set; }
public bool IsTeacher { get; set; }
public bool IsParent { get; set; }
public bool IsOrg { get; set; }
public bool IsLeaner { get; set; }
public string ToUserStr
{
get
{
List<string> strArr = new List<string>();
if (IsLeaner)
{
strArr.Add("学员");
}
if (IsOrg)
{
strArr.Add("机构");
}
if (IsParent)
{
strArr.Add("家长");
}
if (IsTeacher)
{
strArr.Add("老师");
}
return string.Join(",", strArr);
}
}
public int OrgId { get; set; }
public object OrgInfo { get; set; }
public string IsPlatformStr => OrgId == 0 ? "平台" : "机构";
}
现在我们来使用两行代码来搞定对象映射问题:
为了实现操作更方便,多对象映射,处理小中型项目处理的效率很可观
实现对象映射功能的代码如下:
public static T CopyObjValue<T>(this T toobj, Object fromobj) where T : class
{
if (fromobj != null && toobj != null)
{
var otherobjPorps = fromobj.GetType().GetProperties();
foreach (var formp in otherobjPorps)
{
var top = toobj.GetType().GetProperty(formp.Name);
if (top != null)
{
try
{
top.SetValue(toobj, formp.GetValue(fromobj));
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
return toobj;
}
快乐是一种附加品,如果这种附加品本身成了目的,反而会受到减损。 --大白先生