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>
|
2019-03-27 14:46:35 +08:00
|
|
|
|
/// <typeparam name="T">对象类型</typeparam>
|
2019-03-06 16:26:07 +08:00
|
|
|
|
/// <param name="t">复制目标</param>
|
|
|
|
|
/// <param name="s">复制原</param>
|
2019-03-27 14:46:35 +08:00
|
|
|
|
/// <returns></returns>
|
|
|
|
|
public static T CopyFrom<T>(this T t,object s) where T : class {
|
2019-03-06 16:26:07 +08:00
|
|
|
|
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));
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
2019-03-26 08:46:52 +08:00
|
|
|
|
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;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|