Search code examples
c#listobjectgenericsxmldatasource

How to make list item value not reference to the object


my list item that is already added update base on current object (obj) value. how to make list not update or how to copy obj?

    public static void ReadData<T>(string filename, T obj,string node)
    {
        var xmlDocument = new XmlDocument();
        xmlDocument.Load(filename);
        List<T> objectList = new List<T>();
        XmlNodeList xmlNodeList = xmlDocument.SelectNodes("//"+node);

        for (var i = 0; i < xmlNodeList?.Count; i++)
        {
            var j = 0;
            foreach (var objectProperty in obj.GetType().GetProperties())
            {
                if (objectProperty.CanRead)
                {
                    object value;
                    if (objectProperty.PropertyType == typeof(bool))
                    {
                        value = bool.Parse(xmlNodeList[i].ChildNodes[j].InnerText);
                    }
                    else
                    {
                       value= xmlNodeList[i].ChildNodes[j].InnerText;
                    }
                    objectProperty.SetValue(obj, value);
                    j++;
                }
            }
            objectList.Add(obj);
        }

}


Solution

  • 1.You can implement IConeable

    public class ClonableClass : ICloneable
    {
       public object Clone()
       {
          return this.MemberwiseClone();
       }
    }
    

    Now a and b do not refer to the same object.

    var a = new ClonableClass ();
    var b = (ClonableClass)a.Clone();
    

    2.The simplest way to deep clone is to just serialize the object then deserialize it.

    var objStr= JsonConvert.SerializeObject(obj);
    var newObj = JsonConvert.DeserializeObject<T>(objStr);
    

    3.Another way will require brute force coding but you can get every last bit of performance gain. You can just create a new object then assign all properties manually.