重新分配一个类索引数组(引用类型) [英] Reassign an array of classes indexes (reference type)
本文介绍了重新分配一个类索引数组(引用类型)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下代码:
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] 相同的内存区域。
Since the array of classes, Collection, is a reference type. Collection[0] points to same memory region that Collection[1] does.
我的问题是 如何将 Collection [0]值复制到Collection [1],这样我将获得以下输出:
Collection [1] .X 返回1, Collection [0] .X 返回2。
推荐答案
下面是一个示例
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;
}
}
}
}
这篇关于重新分配一个类索引数组(引用类型)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文