【问题标题】:Variable value changing with the change of array in C#变量值随着C#中数组的变化而变化
【发布时间】:2021-12-05 14:19:54
【问题描述】:
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);

我尝试复制到并得到相同的东西

【问题讨论】:

  • 在 C# 中,您使用对对象的引用。克隆数组时,实际上也克隆了指针,因此它们最终指向相同的对象。您需要实现 Clone 并实际克隆您的对象,例如PremiumBill x = temporaryList.OrderBy(...).FirstOrDefault(...).Clone().
  • 这能回答你的问题吗? How do I clone a generic list in C#?

标签: c# arrays variables


【解决方案1】:

您想要的是数组的深拷贝。目前,您拥有的是一个浅拷贝,其中两个数组都指向相同的引用。

下面是一个使用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 };
    }
}

发布了一个答案,因为通过示例这样做更有意义。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 2019-08-27
    • 2015-12-27
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多