我正在使用HtmlTextWriter
将html输出到流中。但是,我错过了写html评论的方法。当然,我可以编写一个扩展方法
public static void WriteComment(this HtmlTextWriter writer, string comment)
{
writer.Write("<!-- ");
writer.WriteEncodedText(comment);
writer.Write(" -->");
}
但这确实感觉有点不雅 - 是否有一些我没有看到的内置方法?
答案 0 :(得分:2)
我可以在检查specification之后争辩说,这些扩展可能会更加正确,
public static void WriteBeginComment(this HtmlTextWriter writer)
{
writer.Write(HtmlTextWriter.TagLeftChar);
writer.Write("!--");
}
public static void WriteEndComment(this HtmlTextWriter writer)
{
writer.Write("--");
writer.Write(HtmlTextWriter.TagRightChar);
}
public static void WriteComment(this HtmlTextWriter writer, string comment)
{
if (
comment.StartsWith(">") ||
comment.StartsWith("->") ||
comment.Contains("--") ||
comment.EndsWith("-"))
{
throw new ArgumentException(
"text does not meet HTML5 specification",
"comment");
}
writer.WriteBeginComment();
writer.Write(comment);
writer.WriteEndComment();
}