2019-03-26 08:46:52 +08:00
|
|
|
|
namespace CommonHelper
|
2019-03-06 16:26:07 +08:00
|
|
|
|
{
|
|
|
|
|
using System;
|
|
|
|
|
|
|
|
|
|
public static class ObjExtend
|
|
|
|
|
{
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// 从目标对象中复制属性的值,执行浅表复制
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="t">复制目标</param>
|
|
|
|
|
/// <param name="s">复制原</param>
|
|
|
|
|
public static void CopyFrom(this object t,object s) {
|
|
|
|
|
foreach(var p in s.GetType().GetProperties()) {
|
|
|
|
|
if(p.CanRead) {
|
|
|
|
|
var tp = t.GetType().GetProperty(p.Name);
|
|
|
|
|
if(tp != null && tp.CanWrite && canConvert(p.PropertyType,tp.PropertyType)) {
|
|
|
|
|
tp.SetValue(t,p.GetValue(s));
|
|
|
|
|
//tp.SetValue(t,Convert.ChangeType(p.GetValue(s),tp.PropertyType));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
/// <summary>
|
2019-03-26 08:46:52 +08:00
|
|
|
|
/// 从目标对象中复制属性的值,执行浅表复制
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <typeparam name="T">对象类型</typeparam>
|
|
|
|
|
/// <param name="t">复制目标</param>
|
|
|
|
|
/// <param name="s">复制原</param>
|
|
|
|
|
/// <returns></returns>
|
|
|
|
|
public static T CopyFrom<T>(this T t,object s) where T : class {
|
|
|
|
|
CopyFrom(t,s);
|
|
|
|
|
return t as T;
|
|
|
|
|
}
|
|
|
|
|
/// <summary>
|
2019-03-06 16:26:07 +08:00
|
|
|
|
/// 判断一个类型是否可以转换为另一个类型
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="source">原类型</param>
|
|
|
|
|
/// <param name="target">目标类型</param>
|
|
|
|
|
private static bool canConvert(Type source,Type target) {
|
|
|
|
|
//引用类型判断
|
|
|
|
|
if(target.IsAssignableFrom(source)) {
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
//Nullable<>类型判断
|
|
|
|
|
//值类型判断
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|