C#通用列表属性设置/添加行为

时间:2011-10-19 16:02:43

标签: c# asp.net generics

我想在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来激活setter,以便列表实际存储在viewstate中。我怀疑有一种更优雅的方式来实现这一点,有没有人有任何建议?干杯

4 个答案:

答案 0 :(得分:3)

调用.Add()你永远不会触发setter。我想,你根本不需要制定者。相反,重写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(新的MoodleCourse);

答案 1 :(得分:1)

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

答案 2 :(得分:1)

如果您希望它在getter中有副作用,请不要使用该属性。相反,只需使用这样的方法:

protected List<MoodleCourse> GetMoodleCourses()
{
    List<MoodleCourse> list = (List<MoodleCourse>)ViewState["MoodleCoursesCreated"];
    if (list == null)
    {
        list = new List<MoodleCourse>();
        ViewState["MoodleCoursesCreated"] = list;
    }
    return list;
}

答案 3 :(得分:1)

你应该在getter中持有相同的引用:

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