[英]Variable value changing with the change of array in C#
PremiumBill x = list.OrderBy(j => j.PostingDate).FirstOrDefault(j => j.PostingDate >= input.PostingDate);
您好,我正在尝试将数组中的值保存在变量中以在数组更改时保留它,但变量的值会随着其更改而更改。 我试过了
PremiumBill[] temporaryList = (PremiumBill[])List.ToArray().Clone();
PremiumBill x = temporaryList.OrderBy(j => j.PostingDate).FirstOrDefault(j => j.PostingDate >= input.PostingDate);
我尝试复制到并得到同样的东西
您想要的是数组的深层副本。 目前,您拥有的是一个浅拷贝,其中两个数组都指向相同的引用。
下面是一个使用ICloneable
接口的深拷贝示例。 执行深度复制有多种方法,我通常更喜欢使用 JSON 进行序列化和反序列化。 此方法适用于可序列化对象,但如果您遇到异常,请改用ICloneable
接口。 您可以参考这个问题Deep Copy with Array 。
public class Program
{
public static void Main()
{
Foo[] foos = new Foo[]
{
new Foo() { Bar = 1 } ,
new Foo() { Bar = 2 } ,
new Foo() { Bar = 3 } ,
};
Foo[] tempFoos = foos.Select(r => (Foo)r.Clone()).ToArray();
foos[0].Bar = 5;
Foo foo1 = tempFoos[0];
Console.WriteLine(foo1.Bar); // outputs 1
}
}
class Foo : ICloneable
{
public int Bar { get; set; }
public object Clone()
{
return new Foo() { Bar = this.Bar };
}
}
发布了一个答案,因为用一个例子这样做更有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.