C# 通用列表属性设置/添加行为
我想在 ASP.NET 用户控件的视图状态中存储通用列表,因此我有以下代码:
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
来激活设置器,以便列表实际上存储在视图状态中。我怀疑有一种更优雅的方法来实现这一点,有人有什么建议吗?干杯
I want to store a generic list in the viewstate in an ASP.NET user control, so I have the following code:
protected List<MoodleCourse> MoodleCoursesCreated
{
get
{
if (ViewState["MoodleCoursesCreated"] == null)
{
return new List<MoodleCourse>();
}
else
{
return (List<MoodleCourse>)ViewState["MoodleCoursesCreated"];
}
}
set
{
ViewState["MoodleCoursesCreated"] = value;
}
}
So to add an item to the list, I call MoodleCoursesCreated.Add(new MoodleCourse);
However it seems then I must do MoodleCourseCreated = MoodleCourseCreated
to activate the setter so the list actually gets stored in the viewstate. I suspect there is a more elegant way to achieve this, does anyone have any suggestions? Cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
调用 .Add() 你永远不会触发设置器。我想,你根本不需要二传手。相反,重写 Add() 方法或创建自己的 AddMoodleCourse(MoodleCourse mudleCourse):
然后调用 MoodleCoursesCreated.AddMoodleCourse(new MoodleCourse);
Calling .Add() you never trigger the setter. I guess, you don't need setter at all. Instead, override Add() method or create your own AddMoodleCourse(MoodleCourse moodleCourse):
and now call MoodleCoursesCreated.AddMoodleCourse(new MoodleCourse);
如果您希望某个属性在 getter 中产生副作用,请不要使用该属性。相反,只需使用这样的方法:
Don't use a property if you want it to have side-effects in the getter. Instead just use a method like this:
你应该在 getter 中保留相同的引用:
you should hold the same reference in the getter: