【发布时间】:2019-07-25 14:17:48
【问题描述】:
首先,我将我的班级添加到列表中:
然后将该类复制到新类,并在更改日期后按照逻辑再次保存在列表中,但已保存在列表中的第一个元素的日期也正在更改。
看下图:
这是我的完整代码:
if (Session["CompanyId"] != null)
{
List<CalendarList> CalendartableList = new List<CalendarList>();
DateTime cldate = Convert.ToDateTime(CalendarList.DateDue);
CalendarList.CompanyId = Convert.ToInt32(Session["CompanyId"]);
CalendarList.Category = 15;
CalendarList.Status = 1;
CalendarList.Identifier = 232;
CalendarList.Quarter = 5;
CalendarList.IsCompleted = false;
CalendarList.CalendarGUID = CalendarList.Description;
CalendartableList.Add(CalendarList);
DateTime po_Date = cldate;
int pi_Count = 0;
while (po_Date.Year == DateTime.Now.Year)
{
pi_Count += 1;
switch (CalendarList.Interval)
{
case "Weekly":
{
po_Date = cldate.AddDays(7 * pi_Count);
break;
}
case "Biweekly":
{
po_Date = cldate.AddDays(14 * pi_Count);
break;
}
case "Monthly":
{
po_Date = cldate.AddMonths(1 * pi_Count);
break;
}
default:
{
po_Date = cldate.AddMonths(3 * pi_Count);
break;
}
}
if (po_Date.Year == DateTime.Now.Year)
{
CalendarList newlist = new CalendarList();
newlist = CalendarList;
newlist.DateDue = po_Date.ToString();
CalendartableList.Add(newlist);
}
}
还有其他方法可以达到同样的效果吗?
【问题讨论】:
-
您必须创建一个副本。您首先要创建一个实际上不是副本的新 CalendarList,然后将其扔掉而不碰它。您将其替换为原始对象。相反,创建一个实际的完整副本(我会给 CalendarList 一个 Clone() 方法,正如史蒂夫建议的那样)。稍微切线,我会敦促您将
DateDue属性(或字段?)设置为DateTime而不是字符串,并且仅在需要将其显示给用户时将其转换为字符串。 -
尝试使用正确的术语。您不会将课程添加到列表中,也不会复制课程。您正在复制和添加 对象。
标签: c# list class collections