Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

c# - Reassign an array of classes indexes (reference type)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...