我想将通用列表存储在ASP.NET用户控件的viewstate中,所以我有以下代码:

    protected List<MoodleCourse> MoodleCoursesCreated
    {
        get
        {
            if (ViewState["MoodleCoursesCreated"] == null)
            {
                return new List<MoodleCourse>();
            }
            else
            {
                return (List<MoodleCourse>)ViewState["MoodleCoursesCreated"];
            }
        }
        set
        {
            ViewState["MoodleCoursesCreated"] = value;
        }
    }


因此,要将项目添加到列表中,我呼叫MoodleCoursesCreated.Add(new MoodleCourse);

但是似乎我必须做MoodleCourseCreated = MoodleCourseCreated来激活设置器,以便列表实际上存储在viewstate中。我怀疑有一个更优雅的方法可以实现这一目标,有人对此有何建议?干杯

最佳答案

调用.Add()永远不会触发设置器。我想,您根本不需要二传手。相反,重写Add()方法或创建自己的AddMoodleCourse(MoodleCourse moodleCourse):

protected void AddMoodleCourse(MoodleCourse moodleCourse)
{
    var courses = ViewState["MoodleCoursesCreated"] as List<MoodleCourse>;
    if (courses == null)
    {
         courses = new List<MoodleCourse>();
         ViewState["MoodleCoursesCreated"] = courses;
    }
    courses.Add(moodleCourse);
}


现在调用MoodleCoursesCreated.AddMoodleCourse(new MoodleCourse);

10-07 19:24