我在项目中遇到这么一个问题,我需要从TopicModel这个类扩展出一个之比TopicModel多一个属性的类,然而TopicModel这个类有一系列的属性,我不希望在新的类里面一个一个重新声明,并且一个一个根据父类的值来赋值,这个时候可以使用反射:

TopicModel
    [DataContract(Name = "topic")]
    public class TopicModel
    {
        /// <summary>
        /// 文章标题
        /// </summary>
        [DataMember(Name = "title")]
        public string Title { get; set; }

        /// <summary>
        /// 文章正文
        /// </summary>
        [DataMember(Name = "content")]
        public string Content { get; set; }

        [DataMember(Name = "author")]
        public string Author { get; set; }

        [DataMember(Name = "board")]
        public string Board { get; set; }

        [DataMember(Name = "quote")]
        public string Quote { get; set; }

        [DataMember(Name = "quoter")]
        public string Quoter { get; set; }

        [DataMember(Name = "id")]
        public int Id { get; set; }

        [DataMember(Name = "reid")]
        public int Reid { get; set; }

        [DataMember(Name = "time")]
        public int Time { get; set; }

        [DataMember(Name = "size")]
        public int Size { get; set; }

        [DataMember(Name = "replies")]
        public int Replies { get; set; }

        [DataMember(Name = "read")]
        public int Read { get; set; }

        [DataMember(Name = "unread")]
        public bool Unread { get; set; }

        [DataMember(Name = "top")]
        public bool Top { get; set; }

        [DataMember(Name = "mark")]
        public bool Mark { get; set; }
    }

 

IndexedTopicModel
    public class IndexedTopicModel : TopicModel
    {
        public int Index { get; set; }

        public IndexedTopicModel(TopicModel topic, int index)
        {
            foreach (var basePropertyInfo in topic.GetType().GetProperties())
            {
                var derivedPropertyInfo = topic.GetType().GetProperty(basePropertyInfo.Name);
                derivedPropertyInfo.SetValue(this, basePropertyInfo.GetValue(topic, null), null);
            }

            Index = index;
        }
    }