Reassign an array of classes indexes (reference type)

最后都变了- 提交于 2019-12-25 18:44:41

问题


Consider the following code:

internal class A
{
     public int X;
}

private void test()
{
     A[] Collection = new A[2];
     Collection[0].X = 1;
     Collection[1] = Collection[0]
     Collection[0] = new A();
     Collection[0].X = 2;
     //The code above produces: Collection[1] displays 2, and Collection[0] displays 2.
     //Wanted behaviour: Collection[1] should display 1, and Collection[0] display 2.
}

Since the array of classes, Collection, is a reference type. Collection[0] points to same memory region that Collection[1] does.

My question is, how can i "copy" Collection[0] values to Collection[1] so i get the following output:

Collection[1].X returns 1, and Collection[0].X returns 2.


回答1:


here is a example

internal class A
{
     public int X;
}

private void test()
{
     A[] Collection = new A[2];
     Collection[0].X = 1;
       CopyPropertyValues(Collection[0],Collection[1]);
     Collection[0] = new A();
     Collection[0].X = 2;

}




public static void CopyPropertyValues(object source, object destination)
{
    var destProperties = destination.GetType().GetProperties();

    foreach (var sourceProperty in source.GetType().GetProperties())
    {
        foreach (var destProperty in destProperties)
        {
            if (destProperty.Name == sourceProperty.Name && 
        destProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))
            {
                destProperty.SetValue(destination, sourceProperty.GetValue(
                    source, new object[] { }), new object[] { });

                break;
            }
        }
    }
}



回答2:


You should have class 'A' implement a 'Clone' method and then instead of:

Collection[1] = Collection[0];

use:

Collection[1] = Collection[0].Clone();

Alternatively, you could change class 'A' to a struct, but that would have other unintended consequences.



来源:https://stackoverflow.com/questions/22749081/reassign-an-array-of-classes-indexes-reference-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!