C#类型转换,对象转换
YESWEB开发框架 开发系统时,经常会用到对象互转 ,从一个对象转换为另一个结构匹配的对象,用于映射ORM模型,
该扩展提供了两个方法,
ConvertObject:一个对象转换为另一个对象
ConvertArray:从一个对象数组转换为另一个对象数组
C# 全选
public static class ConvertExections
{
static Dictionary<PropertyInfo, PropertyInfo> GetMapping(PropertyInfo[] source, PropertyInfo[] target)
{
Dictionary<PropertyInfo, PropertyInfo> mapping = new Dictionary<PropertyInfo, PropertyInfo>();
foreach (PropertyInfo p_target in target)
{
PropertyInfo p_source = source.Where(w => string.Equals(w.Name, p_target.Name, System.StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
if (p_source != null)
{
if (p_target.GetSetMethod() == null || p_source.GetGetMethod() == null)
continue;
mapping.Add(p_target, p_source);
}
}
return mapping;
}
public static TTarget ConvertObject<TSource, TTarget>(this TSource obj)
where TSource : class
where TTarget : class, new()
{
PropertyInfo[] property_source = typeof(TSource).GetProperties(BindingFlags.Instance | BindingFlags.Public);
PropertyInfo[] property_target = typeof(TTarget).GetProperties(BindingFlags.Instance | BindingFlags.Public);
// 加载属性映射
var mapping = GetMapping(property_source, property_target);
TTarget result = new TTarget();
foreach (PropertyInfo key in mapping.Keys)
{
var val = mapping[key].GetValue(obj);
key.SetValue(result, val);
}
return result;
}
public static List<TTarget> ConvertArray<TSource, TTarget>(this List<TSource> data)
where TSource : class
where TTarget : class, new()
{
PropertyInfo[] property_source = typeof(TSource).GetProperties(BindingFlags.Instance | BindingFlags.Public);
PropertyInfo[] property_target = typeof(TTarget).GetProperties(BindingFlags.Instance | BindingFlags.Public);
// 加载属性映射
var mapping = GetMapping(property_source, property_target);
List<TTarget> result = new List<TTarget>();
foreach (var obj in data)
{
TTarget _target = new TTarget();
foreach (PropertyInfo key in mapping.Keys)
{
var val = mapping[key].GetValue(obj);
key.SetValue(_target, val);
}
result.Add(_target);
}
return result;
}
}
版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
post 张国生