mardi 1 décembre 2015

Setting a Property via Reflection in a copied List updates original list

I'm experiencing a problem in my C# code and I'm sure it has to do with the way I'm using reflection, but I'm not sure how to fix it.

To the best of my knowledge, if I have:

List1 = List<MyClass>

and use a syntax similar to

List2 = new List<MyClass>(List1);

Then List2 should be a copy of List1 and any updates made to it should not reflect in the original list.

That being the case, consider the following test code:

public class Fake
{
    public string MyVal { get; set; }
}

public List<Fake> List1;
public List<Fake> List2;

public void UpdateClassTest()
{
    List1 = new List<Fake>() {new Fake() { MyVal = "hello" } };

    List2 = new List<Fake>(List1);
    string propName;

    System.Type type = typeof(Fake);
    foreach (System.Reflection.PropertyInfo pi in type.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
    {
        propName = pi.Name;
        List2.ForEach(f => pi.SetValue(f, "Good Bye"));
    }
}

When I run this Both List1[0] and List2[0] get updated to "Good Bye", but I would assume List1 would not be affected by the changes I'm making to List2.

What am I doing wrong or not understanding here?





Aucun commentaire:

Enregistrer un commentaire