Clone derived class from base class method

后端 未结 7 2315
萌比男神i
萌比男神i 2021-02-08 17:09

I have an abstract base class Base which has some common properties, and many derived ones which implement different logic but rarely have additional fields.

<
7条回答
  •  萌比男神i
    2021-02-08 17:58

    If performance is not important for your case, you can simplify your code by creating just one general clone method which can clone whatever to whatever if properties are same:

    Base base = new Base(){...};
    Derived derived = XmlClone.CloneToDerived(base);
    
    
    public static class XmlClone
    {
        public static D CloneToDerived(T pattern)
            where T : class
        {
            using (var ms = new MemoryStream())
            {
                using (XmlWriter writer = XmlWriter.Create(ms))
                {
                    Type typePattern = typeof(T);
                    Type typeTarget = typeof(D);
    
                    XmlSerializer xmlSerializerIn = new XmlSerializer(typePattern);
                    xmlSerializerIn.Serialize(writer, pattern);
                    ms.Position = 0;
                    XmlSerializer xmlSerializerOut = new XmlSerializer(typeTarget, new XmlRootAttribute(typePattern.Name));
                    D copy = (D)xmlSerializerOut.Deserialize(ms);                    
                    return copy;
                }
            }
        }
    }
    

提交回复
热议问题