好的,我是业余程序员,只是写了这个.它完成了工作,但我想知道它有多糟糕,可以做些什么改进.
[请注意,这是涂鸦CMS的Chalk扩展.]
public string PostsAsSlides(PostCollection posts,int PostsPerSlide) { StringBuilder sb = new StringBuilder(); decimal slides = Math.Round((decimal)posts.Count / (decimal)PostsPerSlide,3); int NumberOfSlides = Convert.ToInt32(Math.Ceiling(slides)); for (int i = 0; i < NumberOfSlides; i++ ) { int PostCount = 0; sb.Append("<div class=\"slide\">\n"); foreach (Post post in posts.Skip<Post>(i * PostsPerSlide)) { PostCount += 1; string CssClass = "slide-block"; if (PostCount == 1) CssClass += " first"; else if (PostCount == PostsPerSlide) CssClass += " last"; sb.Append(string.Format("<div class=\"{0}\">\n",CssClass)); sb.Append(string.Format("<a href=\"{0}\" rel=\"prettyPhoto\" title=\"{1}\"><img src=\"{2}\" alt=\"{3}\" /></a>\n",post.Custom("Large Image"),post.MetaDescription,post.ImageUrl,post.Title)); sb.Append(string.Format("<a class=\"button-launch-website\" href=\"{0}\" target=\"_blank\">Launch Website</a>\n",post.Custom("Website Url"))); sb.Append("</div><!--.slide-block-->\n"); if (PostCount == PostsPerSlide) break; } sb.Append("</div><!--.slide-->\n"); } return sb.ToString(); }
解决方法
使用
HtmlTextWriter而不是StringBuilder来编写HTML:
StringBuilder sb = new StringBuilder(); using(HtmlTextWriter writer = new HtmlTextWriter(new StringWriter(sb))) { writer.WriteBeginTag("div"); writer.WriteAttribute("class","slide"); //... } return sb.ToString();
我们不想使用非结构化的写入程序来编写结构化数据.
将内循环的身体打破一个单独的例程:
foreach(...) { WritePost(post,writer); } //snip private void WritePost(Post post,HtmlTextWriter writer) { //write single post }
这使得它可以测试和更容易修改.
使用数据结构来管理CSS类.
而不是添加一个空格的额外的类名称,并希望所有行都在最后,保持列表< string>的类名根据需要添加和删除,然后调用:
List<string> cssClasses = new List<string>(); //snip string.Join(" ",cssClasses.ToArray());