C# 父类转换为子类公有方法
public static class ClassConvertor
{
/// <summary>
/// 父类对象转为子类对象
/// </summary>
/// <typeparam name="TChild"></typeparam>
/// <typeparam name="TParent"></typeparam>
/// <param name="parent"></param>
/// <returns></returns>
public static TChild ConvertChild<TChild, TParent>(TChild child,TParent parent) where TChild : TParent, new()
{
var parentType = typeof(TParent);
var properties = parentType.GetProperties();
foreach (var propertity in properties)
{
if (propertity.CanRead && propertity.CanWrite)
{
propertity.SetValue(child, propertity.GetValue(parent, null), null);
}
}
return child;
}
}
调用
var child = ClassConvertor.ConvertChild<Child,Parent>(p, new Child());
//然后再给child的自有属性复制
网友评论