Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/259.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 变量数据在使用过程中丢失 出身背景_C# - Fatal编程技术网

C# 变量数据在使用过程中丢失 出身背景

C# 变量数据在使用过程中丢失 出身背景,c#,C#,我正在构建一个邮件程序,它接受表单中的标题、标签和数据,然后将多个部分合并到电子邮件正文中并转发。为了方便起见,我创建了一个类MailSection,其中包括一个字符串、两个字符串列表和一个bool。将数据添加到类之后,我将该类的实例添加到该类的列表中,并开始下一节。不幸的是,在开始下一节之前清除数据也会清除上一个实例中的数据 示例代码 公共类邮件部分 { 公共字符串节标题{get;set;} 公共列表标签{get;set;} 公共列表数据{get;set; 公共布尔表{get;set;} }

我正在构建一个邮件程序,它接受表单中的标题、标签和数据,然后将多个部分合并到电子邮件正文中并转发。为了方便起见,我创建了一个类
MailSection
,其中包括一个字符串、两个字符串列表和一个bool。将数据添加到类之后,我将该类的实例添加到该类的列表中,并开始下一节。不幸的是,在开始下一节之前清除数据也会清除上一个实例中的数据

示例代码
公共类邮件部分
{
公共字符串节标题{get;set;}
公共列表标签{get;set;}
公共列表数据{get;set;
公共布尔表{get;set;}
}
在页面代码的其他位置

List<string> labels = new List<string>();
List<string> data = new List<string>();
List<MailSection> mailSections = new List<MailSection>();

//section 1
labels.Add("Name");
data.Add("Some Customer");
labels.Add{"Email");
data.Add("Some.Customer@somedomain.com");
mailSections.Add(new MailSection("Customer Info",labels,data,false));
//Here, the data is still intact.
labels.Clear();
data.Clear();
//Here, I expect labels and data to be clear. 
//Unfortunately, this also clears the data in any instance of mailSection
列表标签=新列表();
列表数据=新列表();
List mailSections=新列表();
//第一节
标签。添加(“名称”);
数据。添加(“某些客户”);
标签。添加{“电子邮件”);
添加一些。Customer@somedomain.com");
添加(新邮件部分(“客户信息”、标签、数据、假));
//在这里,数据仍然完好无损。
标签。清除();
data.Clear();
//在这里,我希望标签和数据是清晰的。
//不幸的是,这也会清除mailSection任何实例中的数据
我试过的
我尝试过使MailSection类成为一次性的,并且我尝试过使用一个单独的
MailSection实例,我将添加并重置该实例。

是的,因为MailSection的所有实例都指向标签和数据的同一实例

解决方案:

创建的新实例

List<string> labels = new List<string>();
List<string> data = new List<string>();
列表标签=新列表();
列表数据=新列表();

每次对于MailSection的新实例,您都在重复使用相同的列表。除非您在MailSection中复制该列表,否则所有部分都引用您一直清除的相同列表
List<string> labels = new List<string>();
List<string> data = new List<string>();