重新分配类索引数组(引用类型)

时间:2014-03-30 20:01:14

标签: c# arrays reference

请考虑以下代码:

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.
}

由于类数组 Collection 是引用类型。 Collection [0] 指向 Collection [1] 所执行的相同内存区域。

我的问题是, 我怎样才能复制" Collection [0]的值为Collection [1],因此我得到以下输出:

Collection [1] .X 返回1, Collection [0] .X 返回2.

2 个答案:

答案 0 :(得分:1)

这是一个例子

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;
            }
        }
    }
}

答案 1 :(得分:-1)

您应该让“A”类实现“克隆”方法,然后代替:

Collection[1] = Collection[0];

使用:

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

或者,您可以将类“A”更改为结构,但这会产生其他意外后果。