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开发框架网发布内容,转载请附上原文出处连接
张国生
上一篇:C#计算工龄/年龄
下一篇:.net-winform多平台编译设置 csproj配置
评论列表

发表评论

评论内容
昵称:
关联文章

C#类型转换对象转换
C# 使用Newtonsoft对象转JSON字符串的时候日期类型的处理
C# 金额转换,金额数字转换人民币大写
C#数据类型和常见数据库(SQLServer,MySQL,Oracle,SQLite)的数据类型对应关系
DbDataReader转对象
WPF对象级资源
.NET C#教程初级篇 1-1 基本数据类型及其存储方式
C#判断类型是否可空
C# 中将byte转换为int和int转换为byte
C#8.0 可空引用类型
对象和Datatable互转
C# 根据DataTable 转换成JSON 文本字符串数据
Redis OM .NET Redis对象映射框架
EF 值转换
C# RSA加密(私钥加密、公钥解密、密钥格式转换、支持超大长度分段加密)
c# 将数组或集合 转换成以逗号分隔的字符串
Python对象转json字符串
C#根据文件流判断文件类型
面试官:如果存取IP地址,用什么数据类型比较好 (C#版本)
GZDBHelper中ExecuteDataReader方法,执行SQL语句,并返回指定对象集合

联系我们
联系电话:15090125178(微信同号)
电子邮箱:garson_zhang@163.com
站长微信二维码
微信二维码