停止正则表达式。从修改原始变量代替

问题描述 投票:0回答:1

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

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# regex
1个回答
0
投票

为了拥有课程的副本,您需要创建一个新课程。您可以使用这样的构造函数来实现。我也将您所有的字段都更改为属性。

public class TextClass
{
    // You don't to be able 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

© www.soinside.com 2019 - 2024. All rights reserved.