c# - 停止 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;
}
}
解决方案
为了拥有一个类的副本,您需要创建该类的一个新实例。您可以使用这样的构造函数来做到这一点。此外,我将您的所有字段都更改为属性。
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();
推荐阅读
- ruby-on-rails - Rails:PublicActivity::ORM::ActiveRecord::Activity 没有连接池
- c - 如何在 linux 内核源代码中生成 .ko 文件?
- model-view-controller - 嵌套实体中的自动映射器问题
- spring-boot - SpringBoot Scheduler Cron 过度运行
- vue.js - v-date-picker 双击日期选择问题
- xml - XSD 字符串模式,包括带有拉丁字符的电子邮件
- java - JOptionPane 不打印方法 for 循环变量
- batch-file - 使用批处理脚本读取文本文件并以不同的顺序将特定文本复制到新的文本文件中
- c++ - 内联外部库函数在程序集中会发生什么?
- ant - 我们可以将命令行参数传递给 ant 目标吗