【问题标题】:Clone/copy an array and modify it without affecting the source array? [duplicate]克隆/复制一个数组并修改它而不影响源数组? [复制]
【发布时间】:2021-10-09 00:04:59
【问题描述】:

假设我有一个这样的数组:

string[] words = new string[3];
words[0] = "welcome";
words[1] = "hello";
words[2] = "hey";

我想克隆/复制它并修改它:

string[] new_words = words;
new_words[1] = "hi!";

问题在于它实际上也将words[1] = "hello"; 更改为words[1] = "hi!";,这不是我想要做的。 如何在不影响其来源的情况下复制/克隆数组并对其进行修改?非常感谢!

【问题讨论】:

    标签: c# arrays unity3d


    【解决方案1】:

    克隆应该可以工作:

    var newWords=(string[])words.Clone();
    

    【讨论】:

    • 谢谢!但是,如果我这样做了,我就不能再访问它了吗? newWords[0]... 它会说Cannot apply indexing with [] to an expression of type 'object'
    • 谢谢!这有效!
    • 转换为string[] 后,这不再只是object ...
    【解决方案2】:

    您可以尝试将您的克隆逻辑包装在一个方法中。

    void Swap(string[] arr) => arr[0] = "Temp";

    【讨论】:

    • 谢谢!但是你能告诉我这段代码是做什么的吗? (我不是很熟悉)。
    猜你喜欢
    • 2013-09-17
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 2017-07-31
    • 2020-03-12
    • 2014-08-04
    • 1970-01-01
    • 2018-09-20
    相关资源
    最近更新 更多