如何在.NET 3.5中再次使StringBuilder空?

eug*_*neK 19 c# asp.net .net-3.5

我有一个循环,我根据某些条件创建一些字符串值.我确实将StringBuilder对象放在循环之外,每次我在循环中有新行时,我需要清除此行的StringBuilder附加值.

我如何清除这些?

        StringBuilder sb = new StringBuilder();

        foreach (DataRow row in recipientsList.Rows)
        {
            sb.Length = 0;
            sb.Append("<ul>");
            if (row["needsToActivate"] == "1")
            {
                sb.AppendFormat("<li>{0}</li>", getUsersWithoutActivationTemplate());
            }
            if (row["needsToEnterSite"] == "1")
            {
                sb.AppendFormat("<li>{0}</li>", getUsersWithoutEnteringWebsiteForTwoWeeksTemplate());
            }
            if (row["needsPicture"] == "1")
            {
                sb.AppendFormat("<li>{0}</li>", getUsersWithoutPicturesTemplate());
            }
            if (row["needsText"] == "1")
            {
                sb.AppendFormat("<li>{0}</li>", getUsersWithoutTextTemplate());
            }
            if (row["needsCharacteristic"] == "1")
            {
                sb.AppendFormat("<li>{0}</li>", getUsersWithoutCharateristicsTemplate());
            }
            if (row["needsHobby"] == "1")
            {
                sb.AppendFormat("<li>{0}</li>", getUsersWithoutHobbiesTemplate());
            }
            sb.Append("</ul>");
}
Run Code Online (Sandbox Code Playgroud)

代码接受答案;

Ale*_* K. 50

你可以简单地;

sb.Length = 0;
Run Code Online (Sandbox Code Playgroud)

  • 当你使用很长的字符串时,这不是最好的主意.它可能导致OOM异常.MSDN提供了更多解释:https://social.msdn.microsoft.com/Forums/en-US/db04ba8c-e13e-4d41-89a2-f5601ec3e0ae/outofmemoryexception-setting-stringbuilder-length-to-0?forum=vbgeneral (3认同)
  • 你可以使用这个:sb.Remove(0,sb.Length); (2认同)

Phi*_*ove 13

StringBuilder.Clear(); 是你想要的.

  • 这仅适用于.Net 4. .Net <= 3.5需要使用`sb.Length = 0;` (10认同)
  • .NET 3.5对不起! (3认同)