[英]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.