美文网首页
父类转换为子类

父类转换为子类

作者: 不语翕 | 来源:发表于2020-02-25 21:15 被阅读0次

    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的自有属性复制
    

    相关文章

      网友评论

          本文标题:父类转换为子类

          本文链接:https://www.haomeiwen.com/subject/qjsqchtx.html