简体   繁体   English

C#中随数组变化而变化的变量值

[英]Variable value changing with the change of array in C#

PremiumBill x = list.OrderBy(j => j.PostingDate).FirstOrDefault(j => j.PostingDate >= input.PostingDate);

Hello I'm trying to save a value from the array in a variable to preserve it while the array is changing but the variable's value is changing with its change.您好,我正在尝试将数组中的值保存在变量中以在数组更改时保留它,但变量的值会随着其更改而更改。 I have tried我试过了

PremiumBill[] temporaryList = (PremiumBill[])List.ToArray().Clone();

PremiumBill x = temporaryList.OrderBy(j => j.PostingDate).FirstOrDefault(j => j.PostingDate >= input.PostingDate);

I tried copy to and got the same thing我尝试复制到并得到同样的东西

What you want is a deep-copy of the array.您想要的是数组的深层副本。 Currently, what you have is a shallow copy where both arrays are pointing to the same references.目前,您拥有的是一个浅拷贝,其中两个数组都指向相同的引用。

Below is an example of a deep copy using ICloneable interface.下面是一个使用ICloneable接口的深拷贝示例。 There are different ways to perform a deep copy and what I usually prefer is simply serializing and deserializing using JSON.执行深度复制有多种方法,我通常更喜欢使用 JSON 进行序列化和反序列化。 This method works for serializeable objects but if ever you encounter an exception, use the ICloneable interface instead.此方法适用于可序列化对象,但如果您遇到异常,请改用ICloneable接口。 You may refer to this question Deep Copy with Array .您可以参考这个问题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 };
    }
}

Posted an answer as it makes more sense to do so with an example.发布了一个答案,因为用一个例子这样做更有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM