首页 > 解决方案 > 停止 Regex.Replace 修改原始变量

问题描述

文本变量被 InsertWords() 函数无意修改。如果变量 text.text 是“example ˣ here”,而变量 text.words[0] 是“TEST”,则 InsertWords() 函数会将 text.text 更改为“example TEST here”。我希望 text 变量保持不变,而只有 textCopy 变量发生变化。我该怎么做?为什么 text.text 会发生变化,即使我从未使用过 regex.Replace ?

public class TextClass {

    public List<string> words;
    public string text;
    public string name;
    public string date;
    public string id;

}

public TextClass text;

public TextClass InsertWords()
    {
        Regex regex = new Regex(Regex.Escape("ˣ"));

        TextClass textCopy = text;

        foreach (string word in inputWords)
        {
            textCopy.text = regex.Replace(textCopy.text, word, 1);
        }

        return textCopy;
    }

编辑:我使用这样的功能

public Display display;

display.DisplayText(InsertWords());

public class Display {

    public Text text;

    public void DisplayText (TextClass text_)
    {
        text.text = text_.text;
    }

}

标签: c#string

解决方案


为了拥有一个类的副本,您需要创建该类的一个新实例。您可以使用这样的构造函数来做到这一点。此外,我将您的所有字段都更改为属性。

public class TextClass
{
    // You don't need to set the list externally, just get it to add/remove/iterate
    public List<string> Words { get; } = new List<string>();
    public string Text { get; set; }
    public string Name { get; set; }
    public string Date { get; set; }
    public string Id { get; set; }

    public TestClass() { } // default constructor

    public TestClass(TestClass from) // copy constructor
    {
        Text = from.Text;
        Name = from.Name;
        Date = from.Date;
        Id = from.Id;
        Words.AddRange(from.Words); // this ensures a deep copy of the list
    }    
}

然后你可以做

TextClass textCopy = new TextClass(text);

并且textCopy将是真正的深层副本,text当您分配某些内容时textCopy.Text,它不会生效text.Text

或者,您可以制作这样的复制方法

public class TextClass
{
    // You don't need to set the list externally, just get it to add/remove/iterate
    public List<string> Words { get; } = new List<string>();
    public string Text { get; set; }
    public string Name { get; set; }
    public string Date { get; set; }
    public string Id { get; set; }

    public TestClass Copy()
    {
        var copy = new TestClass()
        {
            Text = this.Text;
            Name = this.Name;
            Date = this.Date;
            Id = this.Id;
        }
        copy.Words.AddRange(this.Words); // this ensures a deep copy of the list
        return copy;
    }    
}

并像这样使用它

TextClass textCopy = text.Copy();

推荐阅读