作者:低调pasta_730 | 2023-07-05 15:42
我有一个循环,我根据某些条件创建一些字符串值.我确实将StringBuilder对象放在循环之外,每次我在循环中有新行时,我需要清除此行的StringBuilder附加值.
我如何清除这些?
StringBuilder sb = new StringBuilder();
foreach (DataRow row in recipientsList.Rows)
{
sb.Length = 0;
sb.Append("
");
if (row["needsToActivate"] == "1")
{
sb.AppendFormat("- {0}
", getUsersWithoutActivationTemplate());
}
if (row["needsToEnterSite"] == "1")
{
sb.AppendFormat("- {0}
", getUsersWithoutEnteringWebsiteForTwoWeeksTemplate());
}
if (row["needsPicture"] == "1")
{
sb.AppendFormat("- {0}
", getUsersWithoutPicturesTemplate());
}
if (row["needsText"] == "1")
{
sb.AppendFormat("- {0}
", getUsersWithoutTextTemplate());
}
if (row["needsCharacteristic"] == "1")
{
sb.AppendFormat("- {0}
", getUsersWithoutCharateristicsTemplate());
}
if (row["needsHobby"] == "1")
{
sb.AppendFormat("- {0}
", getUsersWithoutHobbiesTemplate());
}
sb.Append("
");
}
代码接受答案;
1> Alex K...:
你可以简单地;
sb.Length = 0;
当你使用很长的字符串时,这不是最好的主意.它可能导致OOM异常.MSDN提供了更多解释:https://social.msdn.microsoft.com/Forums/en-US/db04ba8c-e13e-4d41-89a2-f5601ec3e0ae/outofmemoryexception-setting-stringbuilder-length-to-0?forum=vbgeneral
你可以使用这个:sb.Remove(0,sb.Length);
2> PhilPursglov..:
StringBuilder.Clear();
是你想要的.
这仅适用于.Net 4. .Net <= 3.5需要使用`sb.Length = 0;`
.NET 3.5对不起!